var someProp = "propName";
var myObj = {
propName : "Some Value"
}
myObj[someProp];// "Some Value"
样例2
var myDog= "Hunter";
var dogs = {
Fido: "Mutt",
Hunter: "Doberman",
Snoopie: "Beagle"
};
var breed= dogs[myDog];
console.log(breed); //"Doberman"
注意,当我们访问属性时,变量两边不加引号,因为我们用的是变量的值,而不是名称。
练习
Use the playerNumber variable to lookup player 16 in testObj using bracket notation.
代码
// Setup
var testObj = {
12: "Namath",
16: "Montana",
19: "Unitas"
};
// Only change code below this line;
var playerNumber=16; // Change this Line
var player = testObj[playerNumber]; // Change this Line
介绍
250 使用
[ ]
249 使用
.
中括号
[ ]
的另一种使用方法是使用变量来访问对象属性。方法
伪代码
样例1
样例2
注意,当我们访问属性时,变量两边不加引号,因为我们用的是变量的值,而不是名称。
练习
代码
结果显示
来源
https://www.freecodecamp.org/challenges/accessing-objects-properties-with-variables