JavaScript Math.sign() 方法
JavaScript Math.sign() 方法接受一个数值作为参数,计算指定数字的符号并返回结果。
以下是 Math.sign() 方法可能的返回值 -
- 如果提供的数字为正数,则返回 1。
- 如果提供的数字为负数,则返回 -1。
- 如果数字为正零,则返回 0。
- 如果数字为正零,则返回 -0。
- 如果提供的数字为非数字,则返回"NaN"。
语法
以下是 JavaScript Math.sign() 方法的语法 -
Math.sign(x);
参数
此方法仅接受一个参数。下文将对此进行描述 -
- x: 我们要确定符号的数字。
返回值
此方法返回指定数字是负数、正数还是零。
示例 1
在下面的示例中,我们使用 JavaScript Math.sign() 方法检查所提供数字的符号 -
<html> <body> <script> const positiveNumber = 7; const sign = Math.sign(positiveNumber); document.write(sign); </script> </body> </html>
输出
由于提供的数字是正整数,上述程序返回"1"。
示例 2
这里,我们将负整数传递给 Math.sign() 方法 -
<html> <body> <script> const negativeNumber = -5; const sign = Math.sign(negativeNumber); document.write(sign); </script> </body> </html>
输出
如果执行上述程序,结果将返回"-1"。
示例 3
如果提供的数字为 0,则此方法返回结果"0" -
<html> <body> <script> const zero = 0; const sign = Math.sign(zero); document.write(sign); </script> </body> </html>
输出
正如我们在输出中看到的,它返回 0。
示例 4
如果我们向此方法提供非数字参数,它将返回"NaN"作为结果 -
<html> <body> <script> const nonNumeric = "Tutorialspoint"; const sign = Math.sign(nonNumeric); document.write(sign); </script> </body> </html>
输出
正如我们在输出中看到的,它返回"NaN"。

