Target: JS property name can use variable
For example: JS Object object, when assigned to the object properties can be used in the following ways
The
code is as follows:
Var object;
OBJECT.PROP1 = "value1";
object.prop2 = "value2";
You can also use the following methods:
The
code is as follows:
Object.push ({prop1: "value1"});
Object.push ({prop2: "value2"});
Here Prop1 as a property name, you can use it directly, you can also add quotes, such as:
The
code is as follows:
Object.push ({"<span style=" font-family:arial, Helvetica, Sans-serif; ") >prop1</span> ":" 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, for example:
The
code is as follows:
var prop1 = "Prop2";
Object.push ({prop1: "<span style=" font-family:arial, Helvetica, Sans-serif; " >value1</span> "});
So what happens when you access Prop2 via object? For example:
The
code is as follows:
alert (<span style= "font-family:arial, Helvetica, Sans-serif;") >OBJECT.PROP2) </span>
Do not ask, of course, is undefined, and visit Object.prop1 is "value1"
The reason has been said, regardless of the addition of quotes, attributes are treated as constants. Let me give you one more example:
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 don't guess what alert will print?
Of course it's undefined.
Guess what if alert (obj.i) prints?
Of course it's oocss, why? Because obj now has only one attribute I, and through two cycles, the front of the obj.i is covered by the back.
If there is a demand, you need to dynamically add the attribute, that is, the attribute must also be a variable, such as the previous example code, alert (obj.js) is not undefined, but jquery, how to modify it?
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! Treats object obj as an array, which supports assigning attributes and property values to objects using methods similar to subscript. However, objects are still objects and obj.length do not exist.