JavaScript 的数据类型
- string:字符串
- number:数字
- boolean:布尔值
- undefined:未定义
- null:空值
- object:对象(包括数组和函数)
- symbol:符号,独一无二的值(ES6新增)
一、typeof的缺陷
typeof
可以判断 string
、number
、boolean
、undefined
、symbol
、function
等类型,不可以判断 null
、object
类型。
var str = "Hello";
var num = 123;
var bool = true;
var undf;
var nl = null;
var obj = {
name: "John", age: 25};
var arr = [1, 2, 3];
var func = function() {
};
var sym = Symbol("mySymbol");
console.log(typeof str); // 输出:string
console.log(typeof num); // 输出:number
console.log(typeof bool); // 输出:boolean
console.log(typeof undf); // 输出:undefined
console.log(typeof nl); // 输出:object
console.log(typeof obj); // 输出:object
console.log(typeof arr); // 输出:object
console.log(typeof func); // 输出:function
console.log(typeof sym); // 输出:symbol
注意:typeof
无法区分 null
、Object
、Array
。typeof 判断这三种类型返回都是 ‘object’。
二、判断是否为数组
方法1
使用 instanceof
可以判断数据是否为数组。
[] instanceof Array // true
需要注意的是, instanceof
不可以用来判断是否为对象类型,因为数组也是对象。
[] instanceof Object // true
{
} instanceof Object // true
方法2
constructor 也可以判断是否为数组。
[].constructor === Array // true
方法3
Object.prototype.toString.call()
可以获取到对象的各种类型。
Object.prototype.toString.call([]) === '[object Array]' // true
Object.prototype.toString.call({
}) === '[object Object]' // true
此方法还可以用来判断是否为 promise 对象。
let obj = new Promise()
Object.prototype.toString.call(obj) === '[object Promise]' // true
方法4
使用数组的 isArray() 方法判断。
Array.isArray([]) // true
方法5
Object.getPrototypeOf(val) === Array.prototype // true
三、判断是否为对象
方法1(推荐)
Object.prototype.toString.call()
可以获取到对象的各种类型。
Object.prototype.toString.call({
}) === '[object Object]' // true
方法2
Object.getPrototypeOf(val) === Object.prototype // true