Use string variable as object fields

I need to select a property to animate and then make an animation.

The code should look like this:

var prop = "background-color";
switch( val )
{
   case 1: prop = "color";
   case 2: prop = "border-color";
   // ...
}
item.animate( {prop: "#00FF00"}, 1000 );

JavaScript complains about using the "prop" variable.

When i just say

item.animate( {"color": "#00FF00"}, 1000 );

everything is fine.

I think the constant is expected as a declaration of the property of an object.

How can I detect it at runtime?

+3
source share
2 answers

They are equivalent:

// prop is a literal string here,
// not a variable
{prop: "#00FF00"}

and

{"prop": "#00FF00"}

you probably need to do something like this:

var obj = {};
obj[prop]="#0000ff";
item.animate( obj, 1000 );
+5
source

Yes, you're right, JavaScript expects an identifier as the name of a property in an object literal. You will need to create an object and assign the property using square brackets.

var opts = {};
opts[prop] = "#00FF00";
item.animate(opts, 1000);
+2

Source: https://habr.com/ru/post/1772613/


All Articles