Home >Web Front-end >JS Tutorial >Use variables to dynamically set js attribute names_javascript skills

Use variables to dynamically set js attribute names_javascript skills

WBOY
WBOYOriginal
2016-05-16 16:33:281578browse

Target: js attribute names can use variables

Example: js object object, when assigning attributes to the object, you can use the following method

Copy code The code is as follows:

var object;
object.prop1 = "value1";
object.prop2 = "value2";

You can also use the following method:
Copy code The code is as follows:

object.push({prop1:"value1"});
object.push({prop2:"value2"});

Here prop1 is used as the attribute name, which can be used directly or in quotation marks, such as:
Copy code The code is as follows:

object.push({"prop1":"value1"});

The meaning of the expression is the same, that is to say, prop1 can only be recognized as a constant, even if it is a variable, it is useless, for example:
Copy code The code is as follows:

var prop1 = "prop2";
object.push({prop1:"value1"});

What happens when you access prop2 through object in this way? For example:
Copy code The code is as follows:

alert(object.prop2)

No need to ask, of course it is undefined, but accessing object.prop1 is "value1"

The reason has already been mentioned. Regardless of whether quotes are included or not, attributes are treated as constants. Here is another example:

Copy code The code is as follows:

var arr=[];
arr['js']='jquery';
arr['css']='oocss';
var obj={};
for(var i in arr)
{

obj.i=arr[i];
}
alert(obj.js);

Readers, please guess what alert will print?

Of course it is undefined.

Guess again, what will be printed if alert(obj.i)?

Of course it is oocss, why? Because obj now only has one attribute i, and through two loops, the front of obj.i is overwritten by the latter.

If there is demand, you need to add attributes dynamically, that is to say, the attribute must also be a variable. As in the above example code, alert(obj.js) is not undefined, but jquery. How to modify it?

Copy code The code is as follows:

var arr=[];
arr['js']='jquery';
arr['css']='oocss';
var obj={};
for(var i in arr)
{

obj[i]=arr[i];
}
alert(obj.js);


It's that simple! Treat the object obj as an array, which supports using methods similar to subscripts to assign attributes and attribute values ​​to the object. However, the object is still an object, and obj.length does not exist.
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn