Math只是一个对象提供了一些和数学操作相关的属性和方法
Math.ceil()
var num = 1.0001;
console.log(Math.ceil(num)) //2
方法总结
得到一个比当前值大的整数或者和当前值一样的整数
Math.floor()
var num = 1.999999;
console.log(Math.floor(num)); //1
方法总结:
得到一个比当前值小的整数或者和当前值一样的整数
Math.round()
console.log(Math.round(1.3)) //1
console.log(Math.round(Number('aaa'))) //NaN
方法总结:四舍五入
Math.random()
var num = Math.random(); //0~1
(Math.random() * 5 ) +3 //3~8
(Math.random() * 5 ) +5 //5~10
方法总结:
得到一个随机的数字,这个数字是0 ~ 1之间的值,包含0 ,但是不包含1
方法运用
如果想得到0~n的值(包含n)推荐使用Math.round()
如果想得到0~n的值(不包含n)推荐使用Math.floor()
🤔为什么想得到0~n的值(包含n)不推荐使用Math.ceil()呢?
这是因为0出现的机率太低
Math.max()/Math.min()
Math.max()
返回是当前一组数中最大的值
如果不给参数,返回-Infinity
Math.min()
返回当前数组中最小的值
如果不给参数,返回Infinity
以上两个方法,在内部都会执行Number,如果是不可以转成有效值的,会返回NaN
🤔案例运用:购物车商品数量的最大和最小值
聊点无关本文的json格式
var _json = '{"key":value}';
var _json = '{"name":"reci"}';
var _json = '[1,2,3,]' //这样的在JSON中是不可以的
1.类型是字符串
2. key必须加上引号
3.SON中最后一个值后面不能跟逗号
JSON.parse()
JSON.stringIfy()
聊点与本文无关的一些对象方法
var obj = {
name: "lth",
age: 22
};
Object.prototype.add=function(){
console.log(this.name+this.age)
}
for(var i in obj){
console.log(obj[i])
} //会遍历到原型链上去
console.log(obj.hasOwnProperty(add)) //false
console.log(obj.hasOwnProperty('name')) //true
console.log(obj.hasOwnProperty('age')) //true
var a = Object.keys(obj); //不会遍历到原型链上
console.log(a); //返回一个由key组成的数组
var b = Object.values(obj);
console.log(b); //返回一个由value组成的数组
如下图