JavaScript Math abs()方法

下面是一个例子 数学abs() 方法

null
  • 例子:

    <script type= "text/javascript" >
    document.write(Math.abs(-2)+ "<br>" );
    document.write(Math.abs(-2.56));
    </script>

    
    

  • 输出:
    2
    2.56

这个 数学abs() 方法用于返回数字的绝对值。它以一个数字作为参数,并返回其绝对值。

语法:

Math.abs(value)

参数: 此方法接受一个参数,如上所述,如下所述:

  • 价值: 要查找其绝对值的数字将作为参数传递给此函数。

返回: 作为参数传递的数字的绝对值。

下面的示例演示了JavaScript中的Math abs()方法:

  • 例1:
    Input  : Math.abs(-4)
    Output : 4
  • 例2:
    Input : Math.abs(0)
    Output : 0

错误和例外:

  • A. 非数字字符串 作为参数返回传递 .
  • 大于1个整数的数组 作为参数返回传递 .
  • 空变量 作为参数返回传递 .
  • 空字符串 作为参数传递返回0。
  • 空数组 作为参数传递返回0。

上述方法的更多示例代码如下:

项目1:

<!-- POSITIVE NUMBER EXAMPLE -->
<script type= "text/javascript" >
document.write(Math.abs(2)+ "<br>" );
document.write(Math.abs(2.56));
</script>


输出:

2
2.56

项目2:

<!-- STRING EXAMPLE -->
<script type= "text/javascript" >
document.write(Math.abs( "Geeksforgeeks" ));
</script>


输出:

NaN

方案3:

<!-- ADDITION INSIDE FUNCTION EXAMPLE -->
<script type= "text/javascript" >
document.write(Math.abs(7+9));
</script>


输出:

16

支持的浏览器:

  • 谷歌Chrome 1及以上版本
  • Internet Explorer 3及以上版本
  • Firefox 1及以上版本
  • 歌剧3及以上
  • Safari 1及以上
© 版权声明
THE END
喜欢就支持一下吧
点赞14 分享