Javascript中判斷變數是數組還是對象(array還是object)_javascript技巧

來源:互聯網
上載者:User
怎樣判斷一個JavaScript變數是array還是obiect?
答案:
1、如果你只是用typeof來檢查該變數,不論是array還是object,都將返回‘objec'。
此問題的一個可行的答案是是檢查該變數是不是object,並且檢查該變數是否有數字長度(當為空白array時間長度度也可能為0)。
然而,參數對象【arguments object】(傳給制定函數的所有參數),也可能會適用於上述方法,技術上來說,參數對象並不是一個array。
此外,當一個對象有a.length屬性的時候,這個方法也不成立。
複製代碼 代碼如下:

// Real array 正在的數組
var my_array = [];
// Imposter! 冒名頂替的!
var my_object = {};
my_object.length = 0;
// Potentially faulty 潛在的錯誤
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、回答這個問題的另一個答案是用一個更加隱形方法,調用toString( )方法試著將該變數轉化為代表其類型的string。
該方法對於真正的array可行;參數對象轉化為string時返回[object Arguments]會轉化失敗;此外,
對於含有數字長度屬性的object類也會轉化失敗。
複製代碼 代碼如下:

// Real array 真正的數組
var my_array = [];
// Imposter! 冒名頂替的!
var my_object = {};
my_object.length = 0;
// Rock solid 堅如磐石(檢驗函數)
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! 不是數組(array)!
is_this_an_array(my_object);

3、此外,在可能不可靠的多架構DOM環境中,instanceof是個完美合適的操作。
擴充閱讀:"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、對於Javascript 1.8.5(ECMAScript 5),變數名字.isArray( )可以實現這個目的
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!');
}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.