如何在JavaScript對象文字中使用變量做爲鍵?

爲何下面的工做? git

<something>.stop().animate(
    { 'top' : 10 }, 10
);

而這不起做用: es6

var thetop = 'top';
<something>.stop().animate(
    { thetop : 10 }, 10
);

更清楚地說:目前,我沒法將CSS屬性做爲變量傳遞給animate函數。 github


#1樓

我已使用如下內容向對象添加具備「動態」名稱的屬性: 瀏覽器

var key = 'top';
$('#myElement').animate(
   (function(o) { o[key]=10; return o;})({left: 20, width: 100}),
   10
);

key是新屬性的名稱。 函數

傳遞給animate的屬性的對象將爲{left: 20, width: 100, top: 10} spa

這只是使用其餘答案所建議的必填[]表示法,可是用的代碼行卻更少! code


#2樓

{ thetop : 10 }是有效的對象文字。 該代碼將建立一個名爲thetop的對象,該對象的值爲10。如下兩項相同: 對象

obj = { thetop : 10 };
obj = { "thetop" : 10 };

在ES5和更早版本中,不能在對象文字中使用變量做爲屬性名稱。 您惟一的選擇是執行如下操做: ip

var thetop = "top";

// create the object literal
var aniArgs = {};

// Assign the variable property name with a value of 10
aniArgs[thetop] = 10; 

// Pass the resulting object to the animate method
<something>.stop().animate(
    aniArgs, 10  
);

ES6 ComputedPropertyName 定義爲對象文字語法的一部分,這使您能夠編寫以下代碼: 字符串

var thetop = "top",
    obj = { [thetop]: 10 };

console.log(obj.top); // -> 10

您能夠在每一個主流瀏覽器的最新版本中使用此新語法。


#3樓

ES5引用說它不起做用

注意:ES6的規則已更改: https ://stackoverflow.com/a/2274327/895245

規格: http//www.ecma-international.org/ecma-262/5.1/#sec-11.1.5

PropertyName:

  • 標識符名稱
  • 字符串字面量
  • 數值文學

[...]

生產PropertyName:IdentifierName的評估以下:

  1. 返回包含與IdentifierName相同的字符序列的String值。

生產PropertyName:StringLiteral的評估以下:

  1. 返回StringLiteral的SV [String value]。

生產PropertyName:NumericLiteral的評估以下:

  1. 令nbr爲造成NumericLiteral值的結果。
  2. 返回ToString(nbr)。

這意味着:

  • { theTop : 10 }{ 'theTop' : 10 }

    所述PropertyName theTopIdentifierName ,所以它被轉換到'theTop'字符串值,這是字符串值'theTop'

  • 沒法使用變量鍵編寫對象初始值設定項(文字)。

    僅有的三個選項是IdentifierName (擴展爲字符串文字), StringLiteralNumericLiteral (也擴展爲字符串)。


#4樓

使用ECMAScript 2015,您如今能夠直接在對象聲明中使用方括號表示法進行操做:

var obj = {
  [key]: value
}

其中key能夠是任何返回值的表達式(例如,變量)。

所以,您的代碼以下所示:

<something>.stop().animate({
  [thetop]: 10
}, 10)

用做鍵以前將評估thetop


#5樓

在變量周圍添加方括號對我來講很好。 嘗試這個

var thetop = 'top';
<something>.stop().animate(
    { [thetop] : 10 }, 10
);
相關文章
相關標籤/搜索