532

为什么以下工作?

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

而这不起作用:

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

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

4

16 回答 16

842

{ 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 ComputedPropertyName定义为对象文字语法的一部分,它允许您编写如下代码:

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

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

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

于 2010-02-16T16:15:53.807 回答
177

使用ECMAScript 2015,您现在可以使用括号符号直接在对象声明中执行此操作: 

var obj = {
  [key]: value
}

wherekey可以是返回值的任何类型的表达式(例如变量)。

所以这里你的代码看起来像:

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

thetop在用作键之前将评估where 。

于 2016-03-15T23:17:35.197 回答
18

ES5 引用说它不应该工作

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

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

物业名称:

  • 标识符名称
  • 字符串字面量
  • 数字字面量

[...]

产品 PropertyName : IdentifierName 的评估如下:

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

产生式 PropertyName : StringLiteral 的评估如下:

  1. 返回 StringLiteral 的 SV [字符串值]。

产生式 PropertyName : NumericLiteral 的评估如下:

  1. 令 nbr 为形成 NumericLiteral 值的结果。
  2. 返回到字符串(nbr)。

这意味着:

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

    PropertyName theTop是一个,因此IdentifierName它被转换为'theTop'字符串值,即 的字符串值'theTop'

  • 不可能用变量键编写对象初始化器(文字)。

    仅有的三个选项是IdentifierName(扩展为字符串文字) StringLiteral、 和NumericLiteral(也扩展为字符串)。

于 2014-06-16T12:35:46.280 回答
7

ES6 / 2020

如果您尝试使用来自任何其他来源的“key:value”将数据推送到对象,您可以使用以下内容:

let obj = {}
let key = "foo"
let value = "bar"

obj[`${key}`] = value

// A `console.log(obj)` would return:
// {foo: "bar}

// A `typeof obj` would return:
// "object"

希望这可以帮助某人:)

于 2020-07-23T18:23:49.490 回答
5

我使用以下内容将具有“动态”名称的属性添加到对象:

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}

这只是使用[]其他答案推荐的所需符号,但代码行更少!

于 2014-01-10T10:42:26.183 回答
5

在变量周围添加方括号对我很有用。尝试这个

var thetop = 'top';
<something>.stop().animate(
    { [thetop] : 10 }, 10
);
于 2017-05-13T09:30:30.680 回答
4

我找不到一个简单的例子来说明 ES6 和 ES5 的区别,所以我做了一个。两个代码示例都创建完全相同的对象。但是 ES5 示例也适用于较旧的浏览器(如 IE11),而 ES6 示例则不能。

ES6

var matrix = {};
var a = 'one';
var b = 'two';
var c = 'three';
var d = 'four';

matrix[a] = {[b]: {[c]: d}};

ES5

var matrix = {};
var a = 'one';
var b = 'two';
var c = 'three';
var d = 'four';

function addObj(obj, key, value) {
  obj[key] = value;
  return obj;
}

matrix[a] = addObj({}, b, addObj({}, c, d));
于 2019-04-09T23:42:20.597 回答
2

更新:正如评论者指出的那样,任何支持箭头函数的 JavaScript 版本将支持({[myKey]:myValue}),所以这个答案没有实际的用例(事实上,它可能会在一些奇怪的极端情况下中断)。

不要使用下面列出的方法。


不敢相信这还没有发布:只需使用带有匿名评估的箭头函数!

完全非侵入性,不会混淆命名空间,并且只需要一行:

myNewObj = ((k,v)=>{o={};o[k]=v;return o;})(myKey,myValue);

演示:

var myKey="valueof_myKey";
var myValue="valueof_myValue";
var myNewObj = ((k,v)=>{o={};o[k]=v;return o;})(myKey,myValue);
console.log(myNewObj);

在还不支持新语法的环境中很有用{[myKey]: myValue},例如——显然;我刚刚在我的 Web 开发者控制台上验证了它——Firefox 72.0.1,发布于 2020 年 1 月 8 日。 我的立场是正确的;只需将东西放在括号中即可。

(我敢肯定,您可能会做出一些更强大/可扩展的解决方案或任何涉及巧妙reduce使用全部内联)


自从 OP 十年前提出这个问题以来,这并不重要,而是为了完整起见并证明它是如何准确地 回答所述问题,我将在原始上下文中展示这一点:

var thetop = 'top';
<something>.stop().animate(
    ((k,v)=>{o={};o[k]=v;return o;})(thetop,10), 10
);
于 2020-01-11T01:46:43.160 回答
1

给定代码:

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

翻译:

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

如您所见,{ thetop : 10 }声明没有使用变量thetop。相反,它使用名为 的键创建一个对象thetop。如果您希望键是变量的值thetop,那么您将不得不在周围使用方括号thetop

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

ES6 引入了方括号语法。在早期版本的 JavaScript 中,您必须执行以下操作:

var thetop = 'top';
var config = (
  obj = {},
  obj['' + thetop] = 10,
  obj
); // config.top = 10
<something>.stop().animate(config, 10);
于 2017-10-09T18:29:06.820 回答
1

2020 年更新/示例...

一个更复杂的例子,使用括号和文字......你可能不得不做的事情,例如 vue/axios。将文字包裹在括号中,所以

[`...`]

{
    [`filter[${query.key}]`]: query.value,  // 'filter[foo]' : 'bar'
}
于 2020-02-05T17:34:43.250 回答
1

你也可以这样尝试:

let array1 = [{
    "description": "THURSDAY",
    "count": "1",
    "date": "2019-12-05"
},
{
    "description": "WEDNESDAY",
    "count": "0",
    "date": "2019-12-04"
}]
let res = array1.map((value, index) => {
    return { [value.description]: { count: value.count, date: value.date } }
})
console.log(res);

于 2019-12-06T06:11:55.990 回答
0

如果您希望对象键与变量名相同,ES 2015 中有一个简写 方式。ECMAScript 2015 中的新符号

var thetop = 10;
var obj = { thetop };
console.log(obj.thetop); // print 10
于 2019-02-13T08:01:12.707 回答
0

分配键的 ES5 实现如下:

var obj = Object.create(null),
    objArgs = (
      (objArgs = {}),
      (objArgs.someKey = {
        value: 'someValue'
      }), objArgs);

Object.defineProperties(obj, objArgs);

我附上了一个我用来转换为裸对象的片段。

var obj = {
  'key1': 'value1',
  'key2': 'value2',
  'key3': [
    'value3',
    'value4',
  ],
  'key4': {
    'key5': 'value5'
  }
}

var bareObj = function(obj) {

  var objArgs,
    bareObj = Object.create(null);

  Object.entries(obj).forEach(function([key, value]) {

    var objArgs = (
      (objArgs = {}),
      (objArgs[key] = {
        value: value
      }), objArgs);

    Object.defineProperties(bareObj, objArgs);

  });

  return {
    input: obj,
    output: bareObj
  };

}(obj);

if (!Object.entries) {
  Object.entries = function(obj){
    var arr = [];
    Object.keys(obj).forEach(function(key){
      arr.push([key, obj[key]]);
    });
    return arr;
  }
}

console(bareObj);

于 2018-10-02T02:43:13.283 回答
0

你可以这样做:

var thetop = 'top';
<something>.stop().animate(
    new function() {this[thetop] = 10;}, 10
);
于 2019-02-13T12:19:01.477 回答
-1

这样您也可以实现所需的输出

var jsonobj={};
var count=0;
$(document).on('click','#btnadd', function() {
    jsonobj[count]=new Array({ "1"  : $("#txtone").val()},{ "2"  : $("#txttwo").val()});
    count++;
    console.clear();
    console.log(jsonobj);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span>value 1</span><input id="txtone" type="text"/>
<span>value 2</span><input id="txttwo" type="text"/>
<button id="btnadd">Add</button>

于 2018-03-28T10:03:42.710 回答
-1

您可以为 ES5 执行以下操作:

var theTop = 'top'
<something>.stop().animate(
  JSON.parse('{"' + theTop + '":' + JSON.stringify(10) + '}'), 10
)

或提取到一个函数:

function newObj (key, value) {
  return JSON.parse('{"' + key + '":' + JSON.stringify(value) + '}')
}

var theTop = 'top'
<something>.stop().animate(
  newObj(theTop, 10), 10
)
于 2018-10-09T00:01:04.187 回答