jquery - Using a variable for a key in a JavaScript object literal -
why following work?
<something>.stop().animate( { 'top' : 10 }, 10 );
whereas doesn't work:
var thetop = 'top'; <something>.stop().animate( { thetop : 10 }, 10 );
to make clearer: @ moment i'm not able pass css property animate function variable.
{ thetop : 10 }
valid object literal. code create object property named thetop
has value of 10. both following same:
obj = { thetop : 10 }; obj = { "thetop" : 10 };
in es5 , earlier, cannot use variable property name inside object literal. option following:
var thetop = "top"; // create object literal var aniargs = {}; // assign variable property name value of 10 aniargs[thetop] = 10; // pass resulting object animate method <something>.stop().animate( aniargs, 10 );
es6 defines computedpropertyname part of grammar object literals, allows write code this:
var thetop = "top", obj = { [thetop]: 10 }; console.log(obj.top); // -> 10
you can test drive new syntax in recent versions of firefox, chrome , microsoft edge.
Comments
Post a Comment