在JavaScript中,我們可以使用Math對象的abs()方法來求一個數的絕對值。
語法:
Math.abs(x)
說明:
abs,也就是absolute的縮寫,這樣你也很容易記住這個方法。
舉例:
在線測試
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script type="text/javascript">
document.write("4的絕對值是" + Math.abs(4) + "<br/>");
document.write("-4的絕對值是" + Math.abs(-4));
</script>
</head>
<body>
</body>
</html>
在浏覽器預覽效果如下: