動態變數屬性名稱
有時,屬性名稱需要儲存到變數中。在這個例子中,我們詢問使用者需要查詢哪個單詞,然後從我命名為 dictionary
的物件中提供結果。
var dictionary = {
lettuce: 'a veggie',
banana: 'a fruit',
tomato: 'it depends on who you ask',
apple: 'a fruit',
Apple: 'Steve Jobs rocks!' // properties are case-sensitive
}
var word = prompt('What word would you like to look up today?')
var definition = dictionary[word]
alert(word + '\n\n' + definition)
注意我們如何使用 []
括號表示法來檢視名為 word
的變數; 如果我們使用傳統的 .
表示法,那麼它將按字面意思取值,因此:
console.log(dictionary.word) // doesn't work because word is taken literally and dictionary has no field named `word`
console.log(dictionary.apple) // it works! because apple is taken literally
console.log(dictionary[word]) // it works! because word is a variable, and the user perfectly typed in one of the words from our dictionary when prompted
console.log(dictionary[apple]) // error! apple is not defined (as a variable)
你還可以通過用字串'apple'
替換變數 word
來使用 []
表示法編寫文字值。請參見[帶有特殊字元或保留字的屬性]示例。
你還可以使用括號語法設定動態屬性:
var property="test";
var obj={
[property]=1;
};
console.log(obj.test);//1
它的作用如下:
var property="test";
var obj={};
obj[property]=1;