filmov
tv
Basic Javascript (84/111) | Accessing Object Properties with Variables | freeCodeCamp

Показать описание
Basic Javascript (84/111) | Accessing Object Properties with Variables | freeCodeCamp
"Another use of bracket notation on objects is to access a property which is stored as the value of a variable. This can be very useful for iterating through an object's properties or when accessing a lookup table.
Here is an example of using a variable to access a property:
var dogs = {
Fido: ""Mutt"", Hunter: ""Doberman"", Snoopie: ""Beagle""
};
var myDog = ""Hunter"";
var myBreed = dogs[myDog];
Another way you can use this concept is when the property's name is collected dynamically during the program execution, as follows:
var someObj = {
propName: ""John""
};
function propPrefix(str) {
var s = ""prop"";
return s + str;
}
var someProp = propPrefix(""Name""); // someProp now holds the value 'propName'
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.
Set the playerNumber variable to 16. Then, use the variable to look up the player's name and assign it to player."
"Another use of bracket notation on objects is to access a property which is stored as the value of a variable. This can be very useful for iterating through an object's properties or when accessing a lookup table.
Here is an example of using a variable to access a property:
var dogs = {
Fido: ""Mutt"", Hunter: ""Doberman"", Snoopie: ""Beagle""
};
var myDog = ""Hunter"";
var myBreed = dogs[myDog];
Another way you can use this concept is when the property's name is collected dynamically during the program execution, as follows:
var someObj = {
propName: ""John""
};
function propPrefix(str) {
var s = ""prop"";
return s + str;
}
var someProp = propPrefix(""Name""); // someProp now holds the value 'propName'
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.
Set the playerNumber variable to 16. Then, use the variable to look up the player's name and assign it to player."