2019-02-19 11:34:27 +03:00

3.1 KiB
Raw Blame History

id, title, challengeType, videoUrl, localeTitle
id title challengeType videoUrl localeTitle
56533eb9ac21ba0edf2244c9 Accessing Object Properties with Variables 1 使用变量访问对象属性

Description

对象的括号表示法的另一个用途是访问存储为变量值的属性。这对于迭代对象的属性或访问查找表非常有用。以下是使用变量访问属性的示例:
var dogs = {
Fido“Mutt”Hunter“Doberman”Snoopie“Beagle”
};
var myDog =“猎人”;
var myBreed = dogs [myDog];
的console.logmyBreed; //“杜宾犬”
另一种可以使用此概念的方法是在程序执行期间动态收集属性的名称,如下所示:
var someObj = {
propName“约翰”
};
function propPrefixstr{
var s =“prop”;
return s + str;
}
var someProp = propPrefix“Name”; // someProp现在保存值'propName'
的console.logsomeObj中[someProp]; // “约翰”
请注意,在使用变量名来访问属性时,我们不会使用引号,因为我们使用的是变量的 ,而不是名称

Instructions

使用playerNumber变量使用括号表示法在testObj查找玩家16 。然后将该名称分配给player变量。

Tests

tests:
  - text: <code>playerNumber</code>应该是一个数字
    testString: 'assert(typeof playerNumber === "number", "<code>playerNumber</code> should be a number");'
  - text: 变量<code>player</code>应该是一个字符串
    testString: 'assert(typeof player === "string", "The variable <code>player</code> should be a string");'
  - text: <code>player</code>的价值应该是“蒙大拿”
    testString: 'assert(player === "Montana", "The value of <code>player</code> should be "Montana"");'
  - text: 您应该使用括号表示法来访问<code>testObj</code>
    testString: 'assert(/testObj\s*?\[.*?\]/.test(code),"You should use bracket notation to access <code>testObj</code>");'
  - text: 您不应该直接将值<code>Montana</code>分配给变量<code>player</code> 。
    testString: 'assert(!code.match(/player\s*=\s*"|\"\s*Montana\s*"|\"\s*;/gi),"You should not assign the value <code>Montana</code> to the variable <code>player</code> directly.");'
  - text: 您应该在括号表示法中使用变量<code>playerNumber</code>
    testString: 'assert(/testObj\s*?\[\s*playerNumber\s*\]/.test(code),"You should be using the variable <code>playerNumber</code> in your bracket notation");'

Challenge Seed

// 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

console.info('after the test');

Solution

// solution required