怎樣判斷一個(gè)JavaScript變量是array還是obiect?
答案:
1、如果你只是用typeof來檢查該變量,不論是array還是object,都將返回‘objec'。
此問題的一個(gè)可行的答案是是檢查該變量是不是object,并且檢查該變量是否有數(shù)字長(zhǎng)度(當(dāng)為空array時(shí)長(zhǎng)度也可能為0)。
然而,參數(shù)對(duì)象【arguments object】(傳給制定函數(shù)的所有參數(shù)),也可能會(huì)適用于上述方法,技術(shù)上來說,參數(shù)對(duì)象并不是一個(gè)array。
此外,當(dāng)一個(gè)對(duì)象有a.length屬性的時(shí)候,這個(gè)方法也不成立。
// Real array 正在的數(shù)組
var my_array = [];
// Imposter! 冒名頂替的!
var my_object = {};
my_object.length = 0;
// Potentially faulty 潛在的錯(cuò)誤
function is_this_an_array(param) {
if (typeof param === 'object' && !isNaN(param.length)) {
console.log('Congrats, you have an array!');
}
else {
console.log('Bummer, not an array');
}
}
// Works 成功
is_this_an_array(my_array);
// Works, but is incorrect 成功了,但是不正確
is_this_an_array(my_object);
2、回答這個(gè)問題的另一個(gè)答案是用一個(gè)更加隱蔽的方法,調(diào)用toString( )方法試著將該變量轉(zhuǎn)化為代表其類型的string。
該方法對(duì)于真正的array可行;參數(shù)對(duì)象轉(zhuǎn)化為string時(shí)返回[object Arguments]會(huì)轉(zhuǎn)化失敗;此外,
對(duì)于含有數(shù)字長(zhǎng)度屬性的object類也會(huì)轉(zhuǎn)化失敗。
// Real array 真正的數(shù)組
var my_array = [];
// Imposter! 冒名頂替的!
var my_object = {};
my_object.length = 0;
// Rock solid 堅(jiān)如磐石(檢驗(yàn)函數(shù))
function is_this_an_array(param) {
if (Object.prototype.toString.call(param) === '[object Array]') {
console.log('Congrats, you have an array!');
}
else {
console.log('Bummer, not an array');
}
}
// Works 成功了
is_this_an_array(my_array);
// Not an array, yay! 不是數(shù)組(array)!
is_this_an_array(my_object);
3、此外,在可能不可靠的多框架DOM環(huán)境中,instanceof是個(gè)完美合適的操作。
擴(kuò)展閱讀:"Instanceof Considered Harmful…"
http://perfectionkills.com/instanceof-considered-harmful-or-how-to-write-a-robust-isarray
var my_array = [];
if (my_array instanceof Array) {
console.log('Congrats, you have an array!');
}
4、對(duì)于Javascript 1.8.5(ECMAScript 5),變量名字.isArray( )可以實(shí)現(xiàn)這個(gè)目的
https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/isArray
var my_array = [];
if (Array.isArray(my_array)) {
console.log('Congrats, you have an array!');
}