Target: The attribute name of js can be used with variables
For example: js object object, when assigning attributes to the object, the following method can be used
The code copy is as follows:
var object;
object.prop1 = "value1";
object.prop2 = "value2";
The following method can also be used:
The code copy is as follows:
object.push({prop1:"value1"});
object.push({prop2:"value2"});
Here, prop1 can be used as the attribute name, or quotes can be added, for example:
The code copy is as follows:
object.push({"<span style="font-family: Arial, Helvetica, sans-serif;">prop1</span>":"value1"});
The meanings of expressions are the same, that is, prop1 can only be recognized as a constant, and even if it is a variable, it is useless, for example:
The code copy is as follows:
var prop1 = "prop2";
object.push({prop1:"<span style="font-family: Arial, Helvetica, sans-serif;">value1</span>"});
What happens if you access prop2 through object like this? For example:
The code copy is as follows:
alert(<span style="font-family: Arial, Helvetica, sans-serif;">object.prop2) </span>
Needless to ask, of course it is undefined, but accessing object.prop1 is "value1"
The reason has been mentioned. Regardless of whether or not quotation marks are added, attributes are treated as constants. Let me give you another example:
The code copy 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 wonder what alert will print?
Of course it was undefined.
Please guess again, what will be printed if alert(obj.i)?
Of course it is oocss, why? Because obj now has only one attribute i, and through two loops, the front of obj.i is overwritten by the back.
If there is a requirement, you need to add attributes dynamically, that is, the attribute must be a variable. As in the above example code, alert(obj.js) is not undefined, but jquery. How to modify it?
The code copy 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 object obj as an array, and it supports using methods similar to subscripts to assign attributes and attribute values to objects. However, the object is still an object, and obj.length does not exist.