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

发布于 2024-08-21 22:41:52 字数 278 浏览 11 评论 0原文

为什么下面的方法有效?

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

然而这不起作用:

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

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

Why does the following work?

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

Whereas this doesn't work:

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

To make it even clearer: At the moment I'm not able to pass a CSS property to the animate function as a variable.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(16

下壹個目標 2024-08-28 22:41:52

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

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

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

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

{ thetop : 10 } is a valid object literal. The code will create an object with a property named thetop that has a value of 10. Both the following are the same:

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

In ES5 and earlier, you cannot use a variable as a property name inside an object literal. Your only option is to do the following:

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 ComputedPropertyName as part of the grammar for object literals, which allows you to write the code like this:

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

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

You can use this new syntax in the latest versions of each mainstream browser.

把回忆走一遍 2024-08-28 22:41:52

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

var obj = {
  [key]: value
}

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

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

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

在用作键之前将评估 thetop

With ECMAScript 2015 you are now able to do it directly in object declaration with the brackets notation: 

var obj = {
  [key]: value
}

Where key can be any sort of expression (e.g. a variable) returning a value.

So here your code would look like:

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

Where thetop will be evaluated before being used as key.

空袭的梦i 2024-08-28 22:41:52

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. 返回ToString(nbr)。

这意味着:

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

    完全相同

    PropertyName theTop 是一个 IdentifierName,因此它会转换为 'theTop' 字符串值,这是 'theTop' 的字符串值。

  • 不可能使用变量键编写对象初始值设定项(文字)。

    仅有的三个选项是 IdentifierName(扩展为字符串文字)、StringLiteralNumericLiteral(也扩展为字符串)。< /p>

ES5 quote that says it should not work

Note: rules have changed for ES6: https://stackoverflow.com/a/2274327/895245

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

PropertyName :

  • IdentifierName
  • StringLiteral
  • NumericLiteral

[...]

The production PropertyName : IdentifierName is evaluated as follows:

  1. Return the String value containing the same sequence of characters as the IdentifierName.

The production PropertyName : StringLiteral is evaluated as follows:

  1. Return the SV [String value] of the StringLiteral.

The production PropertyName : NumericLiteral is evaluated as follows:

  1. Let nbr be the result of forming the value of the NumericLiteral.
  2. Return ToString(nbr).

This means that:

  • { theTop : 10 } is the exact same as { 'theTop' : 10 }

    The PropertyName theTop is an IdentifierName, so it gets converted to the 'theTop' string value, which is the string value of 'theTop'.

  • It is not possible to write object initializers (literals) with variable keys.

    The only three options are IdentifierName (expands to string literal), StringLiteral, and NumericLiteral (also expands to a string).

苯莒 2024-08-28 22:41:52

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"

希望这对某人有帮助:)

ES6 / 2020

If you're trying to push data to an object using "key:value" from any other source, you can use something like this:

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"

Hope this helps someone :)

兔姬 2024-08-28 22:41:52

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

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}

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

I have used the following to add a property with a "dynamic" name to an object:

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

key is the name of the new property.

The object of properties passed to animate will be {left: 20, width: 100, top: 10}

This is just using the required [] notation as recommended by the other answers, but with fewer lines of code!

百思不得你姐 2024-08-28 22:41:52

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

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

Adding square bracket around the variable works good for me. Try this

var thetop = 'top';
<something>.stop().animate(
    { [thetop] : 10 }, 10
);
拒绝两难 2024-08-28 22:41:52

你也可以这样尝试:

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

You can also try like this:

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

深居我梦 2024-08-28 22:41:52

我找不到关于 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));

I couldn't find a simple example about the differences between ES6 and ES5, so I made one. Both code samples create exactly the same object. But the ES5 example also works in older browsers (like IE11), wheres the ES6 example doesn't.

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));
慕烟庭风 2024-08-28 22:41:52

更新:正如评论者指出的那样,任何支持箭头函数的 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
);

Update: As a commenter pointed out, any version of JavaScript that supports arrow functions will also support ({[myKey]:myValue}), so this answer has no actual use-case (and, in fact, it might break in some bizarre corner-cases).

Don't use the below-listed method.


I can't believe this hasn't been posted yet: just use arrow functions with anonymous evaluation!

Completely non-invasive, doesn't mess with the namespace, and it takes just one line:

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

demo:

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

useful in environments that don't support the new {[myKey]: myValue} syntax yet, such as—apparently; I just verified it on my Web Developer Console—Firefox 72.0.1, released 2020-01-08. I stand corrected; just wrap the thing in parenthesis and it works.

(I'm sure you could potentially make some more powerful/extensible solutions or whatever involving clever use of reduce, but at that point you'd probably be better served by just breaking out the Object-creation into its own function instead of compulsively jamming it all inline)


not that it matters since OP asked this ten years ago, but for completeness' sake and to demonstrate how it is exactly the answer to the question as stated, I'll show this in the original context:

var thetop = 'top';
<something>.stop().animate(
    ((k,v)=>{o={};o[k]=v;return o;})(thetop,10), 10
);
水中月 2024-08-28 22:41:52

给定代码:

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);

Given code:

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

Translation:

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

As you can see, the { thetop : 10 } declaration doesn't make use of the variable thetop. Instead it creates an object with a key named thetop. If you want the key to be the value of the variable thetop, then you will have to use square brackets around thetop:

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

The square bracket syntax has been introduced with ES6. In earlier versions of JavaScript, you would have to do the following:

var thetop = 'top';
var config = (
  obj = {},
  obj['' + thetop] = 10,
  obj
); // config.top = 10
<something>.stop().animate(config, 10);
一指流沙 2024-08-28 22:41:52

2020 更新/示例...

一个更复杂的示例,使用括号和文字...您可能需要使用 vue/axios 来做一些事情。将文字括在括号中,因此

[`...`]

{
    [`filter[${query.key}]`]: query.value,  // 'filter[foo]' : 'bar'
}

2020 update/example...

A more complex example, using brackets and literals...something you may have to do for example with vue/axios. Wrap the literal in the brackets, so

[ ` ... ` ]

{
    [`filter[${query.key}]`]: query.value,  // 'filter[foo]' : 'bar'
}
游魂 2024-08-28 22:41:52

分配键的 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);

ES5 implementation to assign keys is below:

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

Object.defineProperties(obj, objArgs);

I've attached a snippet I used to convert to bare object.

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);

长安忆 2024-08-28 22:41:52

如果你希望对象键与变量名相同,ES 2015 中有一个简写。
ECMAScript 2015 中的新表示法

var thetop = 10;
var obj = { thetop };
console.log(obj.thetop); // print 10

If you want object key to be same as variable name, there's a short hand in ES 2015.
New notations in ECMAScript 2015

var thetop = 10;
var obj = { thetop };
console.log(obj.thetop); // print 10
扛刀软妹 2024-08-28 22:41:52

你可以这样做:

var thetop = 'top';
<something>.stop().animate(
    new function() {this[thetop] = 10;}, 10
);

You can do it this way:

var thetop = 'top';
<something>.stop().animate(
    new function() {this[thetop] = 10;}, 10
);
旧城空念 2024-08-28 22:41:52

这样你也可以获得想要的输出

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>

This way also you can achieve desired output

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>

七婞 2024-08-28 22:41:52

您可以对 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
)

You could do the following for ES5:

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

Or extract to a function:

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

var theTop = 'top'
<something>.stop().animate(
  newObj(theTop, 10), 10
)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文