* feat(tools): add seed/solution restore script * chore(curriculum): remove empty sections' markers * chore(curriculum): add seed + solution to Chinese * chore: remove old formatter * fix: update getChallenges parse translated challenges separately, without reference to the source * chore(curriculum): add dashedName to English * chore(curriculum): add dashedName to Chinese * refactor: remove unused challenge property 'name' * fix: relax dashedName requirement * fix: stray tag Remove stray `pre` tag from challenge file. Signed-off-by: nhcarrigan <nhcarrigan@gmail.com> Co-authored-by: nhcarrigan <nhcarrigan@gmail.com>
2.4 KiB
2.4 KiB
id, title, challengeType, videoUrl, forumTopicId, dashedName
id | title | challengeType | videoUrl | forumTopicId | dashedName |
---|---|---|---|---|---|
56533eb9ac21ba0edf2244c9 | 通过变量访问对象属性 | 1 | https://scrimba.com/c/cnQyKur | 16165 | accessing-object-properties-with-variables |
--description--
中括号操作符的另一个使用方式是访问赋值给变量的属性。当你需要遍历对象的属性列表或访问查找表(lookup tables)时,这种方式极为有用。
这有一个使用变量来访问属性的例子:
var dogs = {
Fido: "Mutt", Hunter: "Doberman", Snoopie: "Beagle"
};
var myDog = "Hunter";
var myBreed = dogs[myDog];
console.log(myBreed); // "Doberman"
使用此概念的另一种方法是在程序执行期间动态收集属性名称,如下所示:
var someObj = {
propName: "John"
};
function propPrefix(str) {
var s = "prop";
return s + str;
}
var someProp = propPrefix("Name"); // someProp now holds the value 'propName'
console.log(someObj[someProp]); // "John"
提示:当我们通过变量名访问属性的时候,不需要给变量名包裹引号。因为实际上我们使用的是变量的值,而不是变量的名称。
--instructions--
使用变量playerNumber
,通过中括号操作符找到testObj
中playerNumber
为16
的值。然后把名字赋给变量player
。
--hints--
playerNumber
应该是一个数字。
assert(typeof playerNumber === 'number');
变量player
应该是一个字符串。
assert(typeof player === 'string');
player
点值应该是 "Montana"。
assert(player === 'Montana');
你应该使用中括号访问testObj
。
assert(/testObj\s*?\[.*?\]/.test(code));
你不应该直接将Montana
赋给player
。
assert(!code.match(/player\s*=\s*"|\'\s*Montana\s*"|\'\s*;/gi));
你应该在中括号中使用playerNumber
变量。
assert(/testObj\s*?\[\s*playerNumber\s*\]/.test(code));
--seed--
--after-user-code--
if(typeof player !== "undefined"){(function(v){return v;})(player);}
--seed-contents--
// 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
--solutions--
var testObj = {
12: "Namath",
16: "Montana",
19: "Unitas"
};
var playerNumber = 16;
var player = testObj[playerNumber];