对象
获取对象类型
typeof 123; // 'number'
typeof NaN; // 'number'
typeof 'str'; // 'string'
typeof true; // 'boolean'
typeof undefined; // 'undefined'
typeof Math.abs; // 'function'
typeof null; // 'object'
typeof []; // 'object'
typeof {}; // 'object'
包装对象
包装对象的类型是object,和原始值不能使用===判断
console.log(typeof new Number(123)); // object
console.log(typeof new Boolean(true)); // object
console.log(typeof new String('str')); // object
包装对象忘记使用new会变成类型转换函数
console.log(Number('123')); //123 number 相当于parseInt()或parseFloat()
console.log(Boolean('false')); //true boolean
console.log(String(123.45)); // '123.45' string
约定俗成
不要使用new Number()、new Boolean()、new String()创建包装对象
用parseInt()或parseFloat()来转换任意类型到number
用String()来转换任意类型到string,或者直接调用某个对象的toString()方法
- null、undefined没有toString()方法
- 123.toString()会报错,使用123..toString();或(123).toString();
通常不必把任意类型转换为boolean再判断,因为可以直接写if (myVar) {...}
typeof操作符可以判断出number、boolean、string、function和undefined
判断Array要使用Array.isArray(arr)
判断null请使用myVar === null
判断某个全局变量是否存在用typeof window.myVar === 'undefined'
函数内部判断某个变量是否存在用typeof myVar === 'undefined'
时间对象
注意:月份,注意月份范围是0~11,5表示六月
var now = new Date();
now; // Wed Jun 24 2015 19:49:22 GMT+0800 (CST)
now.getFullYear(); // 2015, 年份
now.getMonth(); // 5, 月份,注意月份范围是0~11,5表示六月
now.getDate(); // 24, 表示24号
now.getDay(); // 3, 表示星期三
now.getHours(); // 19, 24小时制
now.getMinutes(); // 49, 分钟
now.getSeconds(); // 22, 秒
now.getMilliseconds(); // 875, 毫秒数
now.getTime(); // 1435146562875, 以number形式表示的毫秒级时间戳
// 创建一个指定日期和时间的Date对象
// 参数依次是年,月,日,时,分,秒,毫秒
var d = new Date(2022, 02, 04, 17, 44, 30, 123);