what to do when the property is a number or integer? I am able to call the value and assign it to a variable. How to assign the property to a variable?
This works ‘’‘var player = testObj[16]; // player = “Montana” ‘’’
but how to assign the property 16 to var playerNumber using bracket notation?
Hi, sorry for reviving this old topic. But could anyone explain in a scenario why this is useful? I passed this challenge but I’m still kind of scratching my head.
I can get the same result by directly referencing var player = testObj[16];. Why should I define another variable just to check this?
I don’t really know the logic behind the codes but I litteraly when line by line
playerNumber should be a number == since we’re looking up player 16 then 16 it is.
The variable player should be a string and player should be “Montana” can be handled by => testObj[16] <== as this will give you player 16’s name
You should be using the variable playerNumber in your bracket notation: swap testObj[16] for testObj[playerNumber]
et voilà
Yes, you can get the value simply by using var player = testObj[16];
But the topic is about Accessing Objects Properties with Variables. Hence you have to use this method here.
First, you have to declare the variable. var playerNumber = 16; //This is the variable we should use to access the object.
Then, we access the object via the var be declared previously. var player = testObj[playerNumber];
I think you already got the point. But just missed the topic.
I am referencing the comment of @sionchen here. I have the similar confusion.
I have understood the logic and have completed the challenge, however, I didn’t understand why we need to do all this. What is the practical use of this?
Also, in the explanation part it says, “This can be very useful for iterating through lists of the object properties”, how can we assign one variable to multiple properties in order to iterate through lists of properties?
It would be great if someone can explain the application of this concept in a practical problem.
I agree that the code could be shorter; however, perhaps you’re using playerNumber to connect to a field in your page/app, and when someone enters a number and tests for that player, then the player variable would kick in and test the object for a match. That would be one way in which you would have to use the two variables.