前端杂货铺Web前端之路

3.js基础--Math

2017-03-13  本文已影响27人  梦见君笑

Math基础

专门用于封装数学计算所用的API或常量

Math不能new


Math的API

1.取整

1>上取整:Math.ceil(num); 只要小数点超过,就取下一个整数。(ceil天花板)

var num = 123.001;

Math.ceil(num); // 124

var num = 123.000;

Math.ceil(num);   //123

2>下取整:Math.floor(num);  舍弃小数部分  (floor 地板)

var num = 123.999

Math.floor(num); //123

Math.floor(num)  vs   parseInt(str);

1.两者都是舍弃小数部分,取整

2.Math.floor(num)只能 对纯数字下取整;parseInt(str)去掉末位的非数字下取整

var n = "123.321a";

parseInt(n);//123

Math.floor(n); //NaN

3>四舍五入取整:Math.round(num)

var num = 123.321;

Math.round(num); // 123

Math.round(num);    vs    n.toFixed(d)

1.Math.round(num)只能取整,不能设定小数位数

   n.toFixed(d)可以按任意小数位数四舍五入

2.Math.round()返回值是数字,可以直接参与数字运算

   n.toFixed(d)返回的是字符串,参与运算需要类型转换。

var n = 123.321;

Math.round(n); // 123

n.toFixed(2); // 123.32

typeof  n.toFixed(2) // string

type of n:查看n的数据类型

2.乘方和开平方

Math.pow(底数,幂);

2的三次方    Math.pow(2,3);   //8

Math.sqrt(num); 开平方

Math.sqrt(4) //2

3.最大值和最小值

1.Math.max(n);

Math.max(1,2,3,4); //4

2.Math.min(n);

Math.min(1,2,3,4); //1

max 和 min 不支持数组类型的参数,解决方案:

Math.max.apply( undefined/math/null , arr );   // 获取数组中的最大值

the first parameter , you pass to apply of any function,will be the this inside that function.but,max doesn't depend on the current context . so anything would in-place of math

4.随机数

Math.random();   0<=r<1

1.从min--max之间随机生成一个随机整数

parseInt ( Math.random()* (max - min + 1 ) + min);

2.从0-max之间生成一个随机数

parseInt(Math.random()*(max+1))

上一篇下一篇

猜你喜欢

热点阅读