1、typeof
- NaN 的数据类型是 number
- 数组(Array)的数据类型是 object
- 日期(Date)的数据类型为 object
- null 的数据类型是 object
- 未定义变量的数据类型为 undefined
typeof [1, 2, 3, 5]; // 返回object
typeof new Date(); // 返回 object
typeof NaN; // 返回 number
typeof function () {} // 返回 function
typeof myCar; // 返回 undefined (如果 myCar 没有声明)
2、undefined 和 null 的区别:
typeof null; // 返回object
typeof undefined; // 返回undefined
null === undefined; //false
null == undefined; // true
3、constructor属性:
constructor 属性返回所有 JavaScript 变量的构造函数。
"John".constructor // 返回函数 String() { [native code] }
(3.14).constructor // 返回函数 Number() { [native code] }
false.constructor // 返回函数 Boolean() { [native code] }
[1,2,3,4].constructor // 返回函数 Array() { [native code] }
{name:'John', age:34}.constructor // 返回函数 Object() { [native code] }
new Date().constructor // 返回函数 Date() { [native code] }
function () {}.constructor // 返回函数 Function(){ [native code] }
(1)可以使用 constructor 属性来查看对象是否为数组 (包含字符串 “Array”):
var fruits = ["Banana", "Orange", "Apple", "Mango"];
function isArray(myArray) {
return myArray.constructor.toString().indexOf("Array") > -1;
}
console.log(isArray(fruits)); // true
(2)可以使用 constructor 属性来查看对象是否为日期 (包含字符串 “Date”):
var myDate = new Date();
function isDate(myDate) {
return myDate.constructor.toString().indexOf("Date") > -1;
}
console.log(isDate(myDate)); // true
4. 类型转换
var a = null;
var b = undefined;
console.log('a:',Number(a),Boolean(a),String(a)); // 0 false "null"
console.log('b:',Number(b),Boolean(b),String(b)); // NaN false "undefined"