JavaScript通过变量设置对象键[重复]

这篇博客探讨了在JavaScript中如何使用变量来设置对象键的问题。作者遇到的问题是,当尝试使用变量作为键时,键的值变成了字符串"key"而非变量的实际值。通过讨论和示例代码,解决方案是首先创建对象,然后再用变量设置键的值。文章还提到了使用ES6新特性来更简洁地设置对象键的方法。
摘要由CSDN通过智能技术生成

本文翻译自:JavaScript set object key by variable [duplicate]

This question already has answers here : 这个问题已经在这里有了答案
Closed 5 years ago . 5年前关闭。

I am building some objects in JavaScript and pushing those objects into an array, I am storing the key I want to use in a variable then creating my objects like so: 我正在用JavaScript构建一些对象并将这些对象推入数组,将要使用的键存储在变量中,然后像下面这样创建对象:

var key = "happyCount";
myArray.push( { key : someValueArray } );

but when I try to examine my array of objects for every object the key is "key" instead of the value of the variable key. 但是,当我尝试检查每个对象的对象数组时,键是"key"而不是变量键的值。 Is there any way to set the value of the key from a variable? 有什么方法可以通过变量设置键的值吗?

Fiddle for better explanation: http://jsfiddle.net/Fr6eY/3/ 小提琴以获得更好的解释: http : //jsfiddle.net/Fr6eY/3/


#1楼

参考:https://stackoom.com/question/mHsN/JavaScript通过变量设置对象键-重复


#2楼

You need to make the object first, then use [] to set it. 您需要先创建对象,然后使用[]进行设置。

var key = "happyCount";
var obj = {};
obj[key] = someValueArray;
myArray.push(obj);

UPDATE 2018: 更新2018:

If you're able to use ES6 and Babel, you can use this new feature: 如果您能够使用ES6和Babel,则可以使用此新功能:

{
    [yourKeyVariable]: someValueArray,
}  

#3楼

Try something like this (check ES6 example at the end of answer) 尝试这样的事情(在答案末尾查看ES6示例)

var yourObject = {};

yourObject[yourKey] = "yourValue";

console.log(yourObject );

example: 例:

var person = {};
var key = "name";

person[key] /* this is same as person.name */ = "John";

console.log(person); // should print  Object { name="John"}

  var person = {}; var key = "name"; person[key] /* this is same as person.name */ = "John"; console.log(person); // should print Object { name="John"} 

In ES6, you can do like this. 在ES6中,您可以这样做。

var key = "name";
var person = {[key]:"John"};
console.log(person); // should print  Object { name="John"}

  var key = "name"; var person = {[key]:"John"}; console.log(person); // should print Object { name="John"} 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值