+ 1
Undefined
Why does this code show undefined when I run it? const user = { name: 'George', age: 31, } let key = 'name'; console.log (user.key);
4 odpowiedzi
+ 6
You can do
user[key]
or
user.name
+ 3
console.log (user.name);
or
console.log (key);
or
console.log (user['name']);
Good Luck
:)
+ 3
Because user has just two properties (name and age), not key.
The value of key is a property of user.
+ 1
user[key]
https://code.sololearn.com/W37hGD6IyXQc/?ref=app
[ ] is used when we don't know the property name in advance.
Reference:
Morpheus JS Fact Series #57:
the post:
https://www.sololearn.com/post/46592/?ref=app
his example code:
https://code.sololearn.com/WT1rPvuw28y2/?ref=app