Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/416.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何将字符串设置为对象的键?_Javascript - Fatal编程技术网

Javascript 如何将字符串设置为对象的键?

Javascript 如何将字符串设置为对象的键?,javascript,Javascript,给定 我想做一个像这样的新物体 this.state = {email: "something", firstName: "something" } const name = "email" const value = this.state[name] 基本上没有其他东西 我试过了 {email: "something"} 这就是{name:“something”}我想要{email:“something”} 但

给定

我想做一个像这样的新物体

this.state = {email: "something", firstName: "something" }
const name = "email"
const value = this.state[name]
基本上没有其他东西

我试过了

{email: "something"}
这就是{name:“something”}我想要{email:“something”}


但是密钥没有附加到变量,我不想让我知道电子邮件

您的代码有两个问题
new
是一个保留字,因此您不能创建名为
new
的变量。第二,你要做的是这样的:

const name='email';
常数myObj={
[姓名]:“某物”
};

请在提供键作为变量时使用[]

const new = {name: value}
var name = "email"
var value = "something"
{[name]: value}
=> {email: "something"}