Math sign javascript что это
Перейти к содержимому

Math sign javascript что это

  • автор:

Math.sign()

The Math.sign() function returns the sign of a number, indicating whether the number is positive, negative or zero.

Syntax

Parameters

Return value

A number representing the sign of the given argument. If the argument is a positive number, negative number, positive zero or negative zero, the function will return 1 , -1 , 0 or -0 respectively. Otherwise, NaN is returned.

Description

Because sign() is a static method of Math , you always use it as Math.sign() , rather than as a method of a Math object you created ( Math is not a constructor).

This function has 5 kinds of return values, 1 , -1 , 0 , -0 , NaN , which represent «positive number», «negative number», «positive zero», «negative zero» and NaN respectively.

The argument passed to this function will be converted to number type implicitly.

Examples

Using Math.sign()

Polyfill

In the above polyfill, no extra type-coercing is needed to make (x > 0) or (x < 0) numbers because subtracting them from each other forces a type conversion from boolean to numbers.

Как работает фунция Math.sign?

Аватар пользователя Aleksey

Можно попрактиковаться с demo на ресурсе 'developer.mozilla.org' чтобы лучше понять работу этой функции.

Аватар пользователя Yaroslav Mikhaylov

Функция Math.sign() принимает на вход число и возвращает одно из пяти значений: 1 , -1 , 0 , -0 или NaN .

Если в нее передано положительное число, функция возвращает 1 , если отрицательное — -1 , если передан ноль (или выражение, вычисляющееся в ноль) — то 0

Math.sign()

Метод Math.sign() возвращает знак числа, указывающий на то, является ли число отрицательным, положительным или нулём.

Синтаксис

Параметры

Описание

Поскольку метод sign() является статическим методом объекта Math , вы всегда должны использовать его как Math.sign() , а не пытаться вызывать метод на созданном экземпляре объекта Math (поскольку объект Math не является конструктором).

Метод может вернуть одно из пяти значений: 1 , -1 , 0 , -0 и NaN , которые представляют, соответственно «положительное число», «отрицательное число», «положительный ноль», «отрицательный ноль» и NaN .

Обратите внимание, что аргумент, переданный в этот метод, будет неявно преобразован в число.

# Math.sign: How to Check if a Number is Positive or Negative in JavaScript

Determining the sign of a number is super easy now with ES6’s Math.sign �� It will indicate whether the number is positive, negative or zero.

# Math.sign Return Value

Math.sign() has 5 possible return values:

Note, the argument passed to this function will be converted to number type implicitly.

# Math.sign Gotcha

A common gotcha is thinking that Math.sign return the converted argument value. Math.sign returns only the sign of a number. It doesn’t return the value.

# Math.sign vs Comparative Operator

Got a real good question from the community:

Why use Math.sign when I can use the comparative operator?

Indeed, if you’re just checking the boolean status, then I’d just use the comparative operator instead of using Math.sign . But where Math.sign shines is it returns a number value. This means you can do calculations.

# Solving an Algorithm Challenge with Math.sign

So it allows me to solve this algorithm challenge: "Reverse an Integer"

This algorithm question is from Leetcode’s "Reverse an Integer". I edited the requirement of the question to simplify our demonstration. To see the actual solution, here’s one from @loia5tqd001

This is actually when I first discovered this function. That’s why I love looking at other people’s solutions. It’s always interesting to see how other people solve something. Even if the solution is bad, I read those too, cause it teaches me what to avoid ��. No knowledge is wasted ��. It’s all expanding my toolkit. Just like those learning machines, the more data you feed, the better it gets. I think my brain is like that too. I need to see a lot of solutions in order for me to get better ��

That’s why in a lot of my tidbits, I cover the different ways of solving something. Because there is never a BEST function. The best way is always dependant on the situation. The larger your toolkit, the higher chance you will find the best way ��

# Negative Zero

So you may notice that Math.sign returns a negative zero:

And your next question is, what the heck is this negative zero ��. Kyle Simpson of "You Don’t Know JS" explains it the best:

Now, why do we need a negative zero, besides academic trivia?

There are certain applications where developers use the magnitude of a value to represent one piece of information (like speed of movement per animation frame) and the sign of that number to represent another piece of information (like the direction of that movement).

In those applications, as one example, if a variable arrives at zero and it loses its sign, then you would lose the information of what direction it was moving in before it arrived at zero. Preserving the sign of the zero prevents potentially unwanted information loss.

# Math.sign Browser Support

Support is great for all modern browsers. Unfortunately, Internet Explorers is too hip to play with the rest of the class. So no support there.

Browser
Chrome
Firefox
Safari
Edge
Internet Explorer

# Code Tidbit for IE

But no worries, here is an alternative code snippet for you. This will work on Internet Explorer and older browsers ��

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *