JavaScript如何使用Math abs()方法?代码实例

2021年3月25日13:05:44 发表评论 616 次浏览

以下是示例数学abs()方法。

Math.abs()方法用于返回数字的绝对值。它以数字作为参数并返回其绝对值。

语法如下:

Math.abs(value)

参数:该方法接受如上所述和以下描述的单个参数:

  • 值:将找到绝对值的数字作为参数传递给此函数。

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

以下示例说明了JavaScript中的Math abs()方法:

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

错误和异常:

  • 一种非数字字符串作为参数返回传递NaN.
  • An大于1的整数数组作为参数返回传递NaN.
  • An空变量作为参数返回传递NaN.
  • An空字符串作为参数传递的返回0。
  • An空数组作为参数传递的返回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( "lsbin" ));          
</script>

输出如下:

NaN

程式3:

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

输出如下:

16

支持的浏览器:

  • 谷歌浏览器
  • IE浏览器
  • 火狐浏览器
  • 歌剧
  • 苹果浏览器

木子山

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: