Identifying Array Object
This question already has an answer here:
In pure JavaScript you can use the following cross browser approach:
if (Object.prototype.toString.call(x) === "[object Array]") {
// is plain array
}
jQuery has special method for that:
if ($.isArray(x)) {
// is plain array
}
You can use instanceof
. Here's some FireBug testing:
test1 = new Object();
test2 = new Array();
test3 = 123;
console.log(test1 instanceof Array); //false
console.log(test2 instanceof Array); //true
console.log(test3 instanceof Array); //false
Best practice is the invocation of Object.prototype.toString()
on the target object, which displays the internal [[Class]]
property name.
Object.prototype.toString.call( x ); // [object Array]
This has the adventage, that it works on any and every object, regardless of if you're working in a multi frame / window environment, which causes problems on using x instanceof Array
.
Newer ES5 implementations, also give you the method Arrays.isArray()
, which returns true
or false
.
Array.isArray( x ); // true
And last but not least, jQuery has its very own .isArray()
method, which also returns a boolean
jQuery.isArray( x ); // true
链接地址: http://www.djcxy.com/p/19296.html
上一篇: 这是用于检查isarray的最佳方法
下一篇: 识别数组对象