--- id: 56533eb9ac21ba0edf2244c9 title: Accessing Object Properties with Variables challengeType: 1 videoUrl: '' localeTitle: 使用变量访问对象属性 --- ## Description
对象的括号表示法的另一个用途是访问存储为变量值的属性。这对于迭代对象的属性或访问查找表非常有用。以下是使用变量访问属性的示例:
var dogs = {
Fido:“Mutt”,Hunter:“Doberman”,Snoopie:“Beagle”
};
var myDog =“猎人”;
var myBreed = dogs [myDog];
的console.log(myBreed); //“杜宾犬”
另一种可以使用此概念的方法是在程序执行期间动态收集属性的名称,如下所示:
var someObj = {
propName:“约翰”
};
function propPrefix(str){
var s =“prop”;
return s + str;
}
var someProp = propPrefix(“Name”); // someProp现在保存值'propName'
的console.log(someObj中[someProp]); // “约翰”
请注意,在使用变量名来访问属性时,我们不会使用引号,因为我们使用的是变量的 ,而不是名称
## Instructions
使用playerNumber变量使用括号表示法在testObj查找玩家16 。然后将该名称分配给player变量。
## Tests
```yml tests: - text: playerNumber应该是一个数字 testString: 'assert(typeof playerNumber === "number", "playerNumber should be a number");' - text: 变量player应该是一个字符串 testString: 'assert(typeof player === "string", "The variable player should be a string");' - text: player的价值应该是“蒙大拿” testString: 'assert(player === "Montana", "The value of player should be "Montana"");' - text: 您应该使用括号表示法来访问testObj testString: 'assert(/testObj\s*?\[.*?\]/.test(code),"You should use bracket notation to access testObj");' - text: 您不应该直接将值Montana分配给变量player 。 testString: 'assert(!code.match(/player\s*=\s*"|\"\s*Montana\s*"|\"\s*;/gi),"You should not assign the value Montana to the variable player directly.");' - text: 您应该在括号表示法中使用变量playerNumber testString: 'assert(/testObj\s*?\[\s*playerNumber\s*\]/.test(code),"You should be using the variable playerNumber in your bracket notation");' ```
## Challenge Seed
```js // Setup var testObj = { 12: "Namath", 16: "Montana", 19: "Unitas" }; // Only change code below this line; var playerNumber; // Change this Line var player = testObj; // Change this Line ```
### After Test
```js console.info('after the test'); ```
## Solution
```js // solution required ```