DIV CSS 佈局教程網

JavaScript 類屬性的訪問方式詳解
編輯:JavaScript基礎知識     

先定義一個物件作為示例:

var fish = {
    head : 1,
    tail : 1,
    feature : {
        speak : false,
        swim : true
    }
}

其一,點運算子:

console.log(fish.head);    // 1
console.log(fish.tail);    // 1
console.log(fish.feature); // Object { head:1, tail:1, feature: Object }

其二,[] 運算子:

console.log(fish['head']); // 1

這裡要注意:中括號內的屬性名必須是字串形式,例如:

console.log(fish[head]); // 錯誤!head 未定義

那麼以下代碼是否正確呢?

for (var prop in fish) {
    console.log(fish[prop]);
}

答案是肯定的。因為遍歷物件屬性時,prop 是以字串型別存在的,依次為 'head'、'tail'、'feature',所以用中括號搭配變數 prop 剛好能正確取到對應屬性值。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved