内置对象
一、什么是内置对象
JavaScript中的对象分为3种:自定义对象、内置对象、浏览器对象,其中前两种是JS基础内容,属于ECMAScript,浏览器对象是JS独有的。
内置对象就是JS语言自带的供开发者使用的对象,提供了一些常用的或是最基本而必要的功能。
二、Math对象
Math对象不是一个构造函数,不需要用new来调用,而是直接使用里面的属性和方法。
Math属性可参见MDN
-
Math.PI
表示一个圆的周长与直径的比例,Math.PI=π≈3.14159 -
Math.max()
函数返回一组数中的最大值,如果给定的参数中至少有一个参数无法被转换成数字,则会返回NaN
。如果没有参数,则结果为- Infinity
(负无穷)
console.log(Math.max(-1, -3, -2));
arguments
是一个类数组对象,包含着传入函数中的所有参数。
使用arguments对象在函数中引用函数的参数。此对象包含传递给函数的每个参数,第一个参数在索引0处。
// 利用对象封装自己的数学对象,里面有PI 最大值和最小值
var myMath = {
PI: 3.141592653,
max: function () {
// arguments接收传递过来的所有实参
var max = arguments[0];
for (var i = 1; i < arguments.length; i++) {
if (arguments[i] > max) {
max = arguments[i];
}
}
return max;
},
min: function () {
var min = arguments[0];
for (var i = 1; i < arguments.length; i++) {
if (arguments[i] < min) {
min = arguments[i];
}
}
return min;
}
}
console.log(myMath.PI);
console.log(myMath.max(1, 5, 9));
console.log(myMath.min(1, 5, 9));
Math.abs()
取绝对值
存在隐式转换,会把字符串型的-1转换成数字型
// 绝对值
console.log(Math.abs(1)); //1
console.log(Math.abs(1)); //1
console.log(Math.abs('-1')); //1 存在隐式转换,会把字符串型的-1转换成数字型
console.log(Math.abs('Elsie')); // NAN
三种取整方法
- Math.floor() 向下取整
// Math.floor 向下取整
console.log(Math.floor(1.1)); //1
console.log(Math.floor(1.9)); //1
- Math.ceil() 向上取整
// Math.ceil 向上取整
console.log(Math.ceil(1.1)); //2
console.log(Math.ceil(1.9)); //2
- Math.round() 其他数字都是四舍五入,但是**.5特殊**,它往大了取(正数、负数均取更大的)
// Math.round()
console.log(Math.round(1.1)); //1
console.log(Math.round(1.5)); //2
console.log(Math.round(1.9)); //2
console.log(Math.round(-1.1)); //-1
console.log(Math.round(-1.5)); //-1
随机数方法 random()
Math.random()
方法返回一个随机的浮点数, 伪随机数范围**[0,1)**,这个方法里面不跟参数
// 随机数random
console.log(Math.random());
// 得到两数之间的随机数
function getRandomArbitrary(min, max) {
return Math.random() * (max - min) + min;
}
// 得到两数之间的随机整数
function getRandomInt(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math