JavaScript的Math对象

原文

  简书原文:https://www.jianshu.com/p/8776ec9cfb58

大纲

  前言
  1、Math对象的值属性
  2、Math对象的函数属性
  3、Math对象的函数的使用

前言

  Math对象是一个全局的对象,不需要定义一个新的对象可直接使用。
  Math 对象用于执行数学任务。
  Math 对象并不像 Date 和 String 那样是对象的类,因此没有构造函数 Math()。

var resultNum1 = Math.abs(testNum);

1、Math对象的值属性

Math.E : 2.718281828459045
Math.LN10 : 2.302585092994046
Math.LN2 : 0.6931471805599453
Math.LOG2E: 0.6931471805599453
Math.LOG10E: 2.302585092994046
Math.PI: 3.141592653589793
Math.SQRT2 : 1.4142135623730951
Math.SQRT1_2: 0.7071067811865476(1/2的平方根)

2、Math对象的函数属性

abs(x);  //绝对值
exp(x); //(e的x次方)
log(x); //(x的自然对数)
max(x1,x2,x3...); //最大值
min(x1,x2,x3...); //最小值
pow(x,y); //(x的y次方)
random(); //(随机数)
sqrt(x); //(x的平方根) //取整
ceil(x);
floor(x);
round(x); //三角函数
cos(x);
sin(x);
tan(x);
acos(x);
asin(x);
atan(x);
atan2(y,2);

3、Math对象的函数的使用

3.1、取整方法:parseInt()、ceil()、floor()、round()

<!--
parseInt():将浮点数转换成整数,直接取整数部分(是JavaScript的内置对象,
不是Math的方法)
ceil():向上取整
floor():向下取整
round():四舍五入取整
-->
<html>
<head>
<title>Test</title>
</head>
<body>
<script>
var myNumber = prompt("Enter the number to be rounded","");
document.write("<h3>The number you entered was "+myNumber+"</h3><br/>");
document.write("<p>The rounding results for this number are </p>");
document.write("<table width=150 border=1>");
document.write("<tr><th>Method</th><th>Result</th></tr>");
document.write("<tr><td>parseInt()</td><td>"+parseInt(myNumber)+"</td></tr>");
document.write("<tr><td>ceil()</td><td>"+Math.ceil(myNumber)+"</td></tr>");
document.write("<tr><td>floor()</td><td>"+Math.floor(myNumber)+"</td></tr>");
document.write("<tr><td>round()</td><td>"+Math.round(myNumber)+"</td></tr>");
document.write("</table>");
</script>
</body>
</html>

JavaScript的Math对象

3.2、获取随机数的方法:random()方法

<!--
随机投掷十次的骰子,获取骰子点数
-->
<html>
<head><title>Test</title></head>
<body>
<script>
var throwCount ;
var diceThrow;
for(throwCount = 0;throwCount<10;throwCount++){
diceThrow = (Math.floor(Math.random() * 6) +1);
document.write(diceThrow +"<br/>");
}
//4 5 4 6 2 1 3 6 4 6

3.3、数的平方方法:pow()方法

<!--
使用pow()方法模拟fix()方法
-->
<html>
<head><title>Test</title></head>
<body>
<script>
function fix(fixNumber, decimalPlaces){
var div = Math.pow(10,decimalPlaces);
fixNumber = Math.round(fixNumber * div)/div;
return fixNumber;
} var number1 = prompt("Enter the number with decimal places you want to fix","");
var number2 = prompt("How many decimal places do you want?",""); document.write(number1 + " fixed to " + number2 + " decimal places is:");
document.write(fix(number1,number2));//234.234234 fixed to 2 decimal places is:234.23
</script>
</body>
</html>

3.4、最大最小方法:min()、max()

/*
但是由于min()和max()方法只能接受任意多个数值参数,而不能将变量传入,所以一般
使用apply来重写这个方法
*/
var values = [1,5,87,6,45,67];
var max = Math.max(values);
console.log(max);//NaN
var max = Math.max.apply(Math,values);
console.log(max);//87

  

上一篇:React组件间通信


下一篇:python中的取整