Use variables to dynamically set js property names

  • 2020-03-30 04:08:24
  • OfStack

Target :js property names can use variables

Example: the js object object, when assigned to the object property can be used in the following way


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

The following can also be used:

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

Prop1 can be used as the property name here, either directly or in quotes, for example:

object.push({"<span style="font-family: Arial, Helvetica, sans-serif;">prop1</span>":"value1"});

The meaning is the same, that is,prop1 can only be recognized as a constant, even if it is a variable. For example:

var prop1 = "prop2";
object.push({prop1:"<span style="font-family: Arial, Helvetica, sans-serif;">value1</span>"});

What happens when you access prop2 through object ? Such as:

alert(<span style="font-family: Arial, Helvetica, sans-serif;">object.prop2) </span>

Don't ask, undefined, of course, and access object.prop1 is "value1"

The reason for this is that attributes are treated as constants with or without quotation marks.


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

The reader does not want to guess what alert prints ?

Of course is undefined.

Again, guess what alert(obj. I) will print if it's alert(obj. I) ?

Oocss, of course, why ? Because obj now has only one attribute I, and through two loops, the one in front of obj. I is overwritten by the one behind.


Related articles: