3.4 KiB
3.4 KiB
id, title, challengeType, guideUrl
id | title | challengeType | guideUrl |
---|---|---|---|
56533eb9ac21ba0edf2244c9 | Accessing Object Properties with Variables | 1 | https://www.freecodecamp.org/guide/certificates/accessing-objects-properties-with-variables |
Description
var dogs = {Another way you can use this concept is when the property's name is collected dynamically during the program execution, as follows:
Fido: "Mutt", Hunter: "Doberman", Snoopie: "Beagle"
};
var myDog = "Hunter";
var myBreed = dogs[myDog];
console.log(myBreed); // "Doberman"
var someObj = {Note that we do not use quotes around the variable name when using it to access the property because we are using the value of the variable, not the name.
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
variable to look up player 16
in testObj
using bracket notation. Then assign that name to the player
variable.
Tests
tests:
- text: <code>playerNumber</code> should be a number
testString: 'assert(typeof playerNumber === "number", "<code>playerNumber</code> should be a number");'
- text: The variable <code>player</code> should be a string
testString: 'assert(typeof player === "string", "The variable <code>player</code> should be a string");'
- text: The value of <code>player</code> should be "Montana"
testString: 'assert(player === "Montana", "The value of <code>player</code> should be "Montana"");'
- text: You should use bracket notation to access <code>testObj</code>
testString: 'assert(/testObj\s*?\[.*?\]/.test(code),"You should use bracket notation to access <code>testObj</code>");'
- text: You should not assign the value <code>Montana</code> to the variable <code>player</code> directly.
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: You should be using the variable <code>playerNumber</code> in your bracket notation
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
var testObj = {
12: "Namath",
16: "Montana",
19: "Unitas"
};
var playerNumber = 16;
var player = testObj[playerNumber];