Arrays of objects in JavaScript

If I do this

var element = {};
alert(element);
element[name] = "stephen";
alert(element.name);

Why doesn’t work element.name?

+3
source share
3 answers

When using a notation bracket (if it is not a variable), it should be in qoutes, for example:

var element = {}; 
alert(element); 
element["name"] = "stephen"; 
alert(element.name);

You cannot check it here . To explain what I mean by “if it's not a variable”, this would also work:

var myVariable = "name";
element[myVariable] = "stephen";
+17
source

Because the name must be in quotation marks. It works:

var element = {};
alert(element);
element['name'] = "stephen";
alert(element.name);

Give it a try.

+8
source

. :

, . , .

obj[name].age // Here the name is a variable, and it can be changed in every page refresh, for example.

obj['name'] = 'Lorenzo', .

, set obj[name], obj['name'] .

0
source

Source: https://habr.com/ru/post/1770782/


All Articles