gpt4 book ai didi

javascript - 如何在 JavaScript 对象文字中使用变量作为键?

转载 作者:太空宇宙 更新时间:2023-11-04 01:24:24 25 4
gpt4 key购买 nike

为什么下面的方法有效?

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

虽然这不起作用:

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

更清楚地说:目前我无法将 CSS 属性作为变量传递给 animate 函数。

最佳答案

{ thetop : 10 } 是有效的对象文字。该代码将创建一个对象,其属性名为 thetop,值为 10。以下两者是相同的:

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

在 ES5 及更早版本中,不能使用变量作为对象字面量内的属性名称。您唯一的选择是执行以下操作:

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 defines CompatedPropertyName 作为对象字面量语法的一部分,它允许您编写如下代码:

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

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

您可以在各个主流浏览器的最新版本中使用此新语法。

关于javascript - 如何在 JavaScript 对象文字中使用变量作为键?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58096458/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com