Dynamically set js property names using variables
Objective: To use variables for js attribute names
For example, when a js object is assigned to the object property, you can use the following method:
The Code is as follows:
Var object;
Object. prop1 = "value1 ";
Object. prop2 = "value2 ";
You can also use the following method:
The Code is as follows:
Object. push ({prop1: "value1 "});
Object. push ({prop2: "value2 "});
Here, prop1 is the property name, which can be used directly or enclosed by quotation marks, for example:
The Code is as follows:
Object. push ({"<span style =" font-family: Arial, Helvetica, sans-serif; "> prop1 </span>": "value1 "});
The expression has the same meaning. That is to say, prop1 can only be recognized as a constant, even if it is a variable, it is useless. For example:
The Code is as follows:
Var prop1 = "prop2 ";
Object. push ({prop1: "<span style =" font-family: Arial, Helvetica, sans-serif; "> value1 </span> "});
In this way, what will happen when you access prop2 through object? For example:
The Code is as follows:
Alert (<span style = "font-family: Arial, Helvetica, sans-serif;"> object. prop2) </span>
You do not need to ask, of course, it is undefined, but the access to object. prop1 is "value1"
The reason has already been said, no matter the quotation marks are added, the attribute will be treated as a constant. Another example is as follows:
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 );
Do not guess what alert will print?
Of course it is undefined.
Let's guess, what will alert (obj. I) print?
Of course it's oocss. Why? Because obj only has one attribute I and uses two loops, the previous one is overwritten by the following one.
If you need to add attributes dynamically, that is to say, the attributes must also be a variable. In the code above, alert (obj. js) is not undefined, but jquery. How can we modify the attributes?
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 );
That's easy! Treat object obj as an array. It supports assigning attributes and attribute values to objects using methods similar to subscripts. However, objects are still objects and obj. length does not exist.