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"。

广告
© . All rights reserved.