判断是否为数组
使用typeof
无法区别数组、对象、null
type | ans |
---|---|
Undefined | “undefined” |
Null | “object” |
Number | “number” |
String | “string” |
Boolean | “boolean” |
Symbol | “symbol” |
function | “function” |
其他对象 | “object” |
typeof NaN === 'number'
typeof Infinity === 'number';
使用instanceof
可以判断某个构造函数的
prototype
所指向的对象是否在另一个要检测的原型链上
object instanceof constructor
var a = [];
a instanceof Array; //true
* 目前的 ES 规范中,只能读取对象的原型而不能改变它,但借助于非标准的proto属
性a.__proto__ = {}
可以更改,返回false
;
* 多个窗口产生多个全局环境,不同的全局环境拥有不同的全局对象,从而拥有不同的内
置类型构造函数;
使用constructor
consr a = [];
a.constructor === Array; // true function Array() {[native code]}
const a = new Array;
a.constructor === Array // true
a.constructor = object;
a.constructor === Array; //false
a instanceof Array // true
* 除了Number
、String
、Boolean
、Symbol
、Undefined
、Null
的基本数据类
型有只读的原生构造函数。对象的 constructor 属性可被修改
使用object
的toString
方法判断
每个继承自
object
的对象都有toString
方法
const a = ['Hello', 'World'];
const o = {x: 'Hello', y: 'World'};
const s = "Hello World";
a.toString() // "Hello World"
o.toString() // "[object object]"
s.toString() // 'Hello World'
Object.prototype.toString.call(a) // "[object Array]"
Object.prototype.toString.call(o) // "[object object]"
Object.prototype.toString.call(s) // "[object String]"
* apply
同理
使用isArray
ES5
新增
Array.isArray([]); //true
Array.isArray([1]); //true
Array.isArray(new Array()); //true
Array.isArray(Array.prototype); //true
* Polyfill
(IE9+
)
if(!Array.isArray) {
Array.isArray = function(arg) {
return Object.prototype.toString.call(arg) === '[object Array]';
}
}
* 可检测iframes