一、Object.prototype.toString.call()(推荐)
Object.prototype.toString.call
可能的返回值如下:
类型 | 结果 |
---|---|
Undefined | "[object Undefined]" |
Null | "[object Null]" |
Boolean | "[object Boolean]" |
Number | "[object Number]" |
String | "[object String]" |
Function | "[object Function]" |
Array | "[object Array]" |
Object | "[object Object]" |
export const typeOf = function(obj) {
return Object.prototype.toString.call(obj).slice(8, -1).toLowerCase()
}
typeOf([]) // array
typeOf(() => { }) // function
二、typeof
typeof
可能的返回值如下:
类型 | 结果 |
---|---|
Undefined | "undefined" |
Null | "object" |
Boolean | "boolean" |
Number | "number" |
String | "string" |
Symbol | "symbol" |
Function | "function" |
Array | "object" |
Object | "object" |
任何其他对象 | "object" |
通过 new 操作符生成的实例的 typeof 都是 ‘object’。有一种特殊情况,Function 的实例的 typeof 是 ‘function’。
由于 Null, Array, Object 和 任何其他对象 用 typeof 都会返回 ‘object’,所以用 typeof 判断数据类型并不是很严谨。
var str = new String('String');
var num = new Number(100);
typeof str; // 'object'
typeof num; // 'object'
var func = new Function();
typeof func; //'function'
三、判断是不是数组
1. Array.isArray()
Array.isArray(obj); //obj是待检测的对象
返回 true 或 false。
2. instanceof
var obj = {"k1":"v1"};
var arr = [1,2];
console.log(obj instanceof Array) //false
console.log(arr instanceof Array) //true