SORU
16 ŞUBAT 2010, Salı


Bir JavaScript bir anahtar için bir değişken kullanarak literal nesnesi

Neden şu işe yarıyor mu?

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

Bu işe yaramaz ise:

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

Bunu daha belirgin hale getirmek için: bir değişken olarak işlev. animate CSS özelliği geçmek mümkün değilim şu an

CEVAP
16 ŞUBAT 2010, Salı


{ thetop : 10 } geçerli bir nesne değişmez. Kod 10 değeri olan bir özellik thetop adında bir nesne oluşturur. Her ikisi de aşağıdaki aynı:

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

ES5 daha eski, ancak bir nesne içinde bir özellik adı sabit değer olarak bir değişken kullanın. Tek seçenek şu: yapmak

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 definesComputedPropertyNamekod yazmak için izin veren nesne harfleri, dilbilgisi bir parçası olarak bu gibi:

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

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

Firefox'un yeni sürümlerinde bu yeni sözdizimi sürücü ve Internet Explorer Teknik mevcut ön test edebilirsiniz.

Bunu Paylaş:
  • Google+
  • E-Posta
Etiketler:

YORUMLAR

SPONSOR VİDEO

Rastgele Yazarlar

  • Amir Parmar

    Amir Parmar

    25 Kasım 2010
  • ipsy Makeup Tips

    ipsy Makeup

    19 ŞUBAT 2009
  • jonathepianist

    jonathepiani

    31 Temmuz 2008