动态变量属性名称

有时,属性名称需要存储到变量中。在这个例子中,我们询问用户需要查找哪个单词,然后从我命名为 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;