Home >Web Front-end >JS Tutorial >Use variables to dynamically set js attribute names_javascript skills
Target: js attribute names can use variables
Example: js object object, when assigning attributes to the object, you can use the following method
The reason has already been mentioned. Regardless of whether quotes are included or not, attributes are treated as constants. Here is another example:
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?
obj[i]=arr[i];
}
alert(obj.js);