JS:包装类、Math对象、Date(日期)对象
一、包装类
-
Number()
、 String()
和Boolean()
的实例都是object类型,它们的PrimitiveValue
属性存储它们的本身值
-
new
出来的基本类型值可以正常参与运算
- 包装类的目的就是为了让基本类型值可以从它们的构造函数的
prototype
上获得方法
var a = new Number(123);
var b = new String('慕课网');
var c = new Boolean(true);
console.log(a);
console.log(typeof a);
console.log(b);
console.log(typeof b);
console.log(c);
console.log(typeof c);
console.log(5 + a);
console.log(b.slice(0, 2));
console.log(c && true);
var d = 123;
console.log(d.__proto__ == Number.prototype);
var e = '慕课网';
console.log(e.__proto__ == String.prototype);
console.log(String.prototype.hasOwnProperty('toLowerCase'));
console.log(String.prototype.hasOwnProperty('slice'));
console.log(String.prototype.hasOwnProperty('substr'));
console.log(String.prototype.hasOwnProperty('substring'));
二、Math对象
- 幂和开方:
Math .pow()
、Math.sqrt()
- 向上取整和向下取整:
Math.ceil()
、Math.floor()
-
Math .round()
可以将一个数字四舍五入为整数
console.log(Math.round ( 3.4));
console.log(Math.round ( 3.5));
console.log(Math.round ( 3.98) );
console.log(Math.round ( 3.49));
var a = 3.7554;
console.log(Math.round(a * 100) / 100);
-
Math .max()
可以得到参数列表的最大值; Math .max()
可以得到参数列表的最大值
注意:
(1)Math.max()要求参数必须是“罗列出来”,而不能是数组
(2)apply
方法可以指定函数的上下文,并且以数组的形式传入“零散值”当做函数的参数
console.log(Math.max(44, 55, 33, 22));
console.log(Math.min(44, 55, 33, 22));
var arr = [3, 4, 4, 3, 2, 2, 1, 3, 5, 7, 4, 3];
console.log(Math.max.apply(null, arr));
console.log(Math.max(...arr));
- 随机数
Math.random()
,为了得到[a, b]区间内的整数,可以使用这个公式
parseInt (Math.random() *(b - a + 1)) +a
console.log(parseInt(Math.random() * 6) + 3);
三、Date(日期)对象
- 使用
new Date()
即可得到当前时间的日期对象,它是object类型值
- 使用
new Date(2020, 11,1)
即可得到指定日期的日期对象,注意第二个参数表示月份,从0开始算,11表示12月
- 也可以是
new Date( '2020-12-01')
这样的写法
- 日期对象的常见的方法
var d = new Date();
console.log('日期', d.getDate());
console.log('星期', d.getDay());
console.log('年份', d.getFullYear());
console.log('月份', d.getMonth() + 1);
console.log('小时', d.getHours());
console.log('分钟', d.getMinutes());
console.log('秒数', d.getSeconds());
- 时间戳表示1970年1月1日零点整距离某时刻的毫秒数;通过
getTime()
方法或者Date.parse()
函数可以将日期对象变为时间戳;通过new Date(时间戳)
的写法,可以将时间戳变为日期对象
var d = new Date();
var timestamps1 = d.getTime();
var timestamps2 = Date.parse(d);
console.log(timestamps1);
console.log(timestamps2);
var dd = new Date(1601536565000);
console.log(dd);