js判斷是否是陣列的方法
阿新 • • 發佈:2018-11-08
1.instanceof
var arr = [1,2,3];
arr instanceof Array
要注意,instanceof Array 只適用於與陣列初始化在相同上下文中才有效,且不能跨iframe
2.Array.isArray()
Array.isArray([1,2,3]);
3.constructor
constructor 在其對應物件的原型下面,是自動生成的。當我們寫一個建構函式的時候,程式會自動新增:建構函式名.prototype.constructor = 建構函式名
var arr = [1,2,3];
arr.constructor === Array
使用constructor是不保險的,因為constructor屬性是可以被修改的,會導致檢測出的結果不正確,且不能跨iframe
a.constructor === Array // true
a.constructor = String // String() { [native code] }
a.constructor === Array // false
另外,當使用該方法判斷其他資料型別時要注意一點是,undefined和null是不能夠判斷出型別的,並且會報錯。因為null和undefined是無效的物件,因此是不會有constructor存在的
4.Object.prototype.toSrtring.call([ ])
另外,當使用該方法判斷其他資料型別時要注意一點是,IE8及IE8以下,undefined和null均為Object,IE9及IE9以上為[object Undefined]
和[object Null]