JavaScript Math.sign() 方法接受数值作为参数,计算指定数字的符号并返回结果。
以下是 Math.sign() 方法的可能返回值 -
- 如果提供的数字为正数,则返回 1。
- 如果提供的数字为负数,则返回 -1。
- 如果 number 为正零,则返回 0。
- 如果 number 为正零,则返回 -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 = "qikepucom";
const sign = Math.sign(nonNumeric);
document.write(sign);
</script>
</body>
</html>
输出
正如我们在输出中看到的,它返回 “NaN”。