Error accessing object property in JavaScript
When accessing an object property, the name of that property cannot be stored in a variable. Let's see why. Suppose we have such an object:
javascriptlet obj = {a: 1, b: 2, c: 3};
Let the variable store the name of the property whose value we want to get:
javascriptlet key = 'a';
Let's try to access the object property using this variable:
javascriptconsole.log(obj.key); // undefined
The above code will not work because
we are actually looking for the property
named 'key', not the property
whose name is stored in the variable
key. That is, in fact, our code
is equivalent to the following:
javascriptconsole.log(obj['key']);
The only way to access an element by key from a variable is to write this variable in square brackets:
javascriptconsole.log(obj[key]);
Задание 1
Fix the error in the following code:
javascriptlet obj = {x: 1, y: 2, z: 3};
let prop = 'x';
console.log(obj.prop);
Задание 2
Fix the error in the following code:
javascriptlet obj = {x: 1, y: 2, z: 3};
let prop = 'x';
console.log(obj['prop']);