开发者

Object arrays in JavaScript

开发者 https://www.devze.com 2023-01-21 08:05 出处:网络
If I do this, var element = {}; alert(element); element[name] = \"stephen\"; alert(element.name); 开发者_如何学编程

If I do this,

var element = {};
alert(element);
element[name] = "stephen";
alert(element.name);
开发者_如何学编程

Why doesn't element.name work?


When using bracket notation, (unless it's a variable) it needs to be in qoutes, like this:

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

You cant test it out here. To explain what I mean by "unless it's a variable", this would also work:

var myVariable = "name";
element[myVariable] = "stephen";


Because name should be in quotes. This works:

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

Try it.


This is the reason why you may want to get an object's property dynamically. For example:

You have a variable, but you can't be sure of its value. The server send you the variable value so you should write like this.

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

But if you want to set obj['name'] = 'Lorenzo' you have to use quotes.

Think like obj[name] is used for set, obj['name'] is used for get.

0

精彩评论

暂无评论...
验证码 换一张
取 消