[英]JavaScript: Add Key and Value to Object Using ES6 {} Shortcut
我有以下对象:
obj = {name: 'Amy',
age: 36,
type: 'sanguine'}
我想向上述对象添加另一个键和值,但我特别想使用 {} 快捷方式来做到这一点。
这是使用 {} 快捷方式的示例:
function test (bloodtype) {
return { bloodtype }
}
test('A')
结果: { index: 0, elem: 22 }
但是尝试使用该快捷方式将血型添加到 obj 不起作用。
function test (bloodtype) {
return obj{ bloodtype }
}
test('A')
错误:
evalmachine.<anonymous>:31
return obj{ bloodtype }
^
SyntaxError: Unexpected token {
我究竟做错了什么?
要使用快捷语法,您首先需要使用对象传播,然后将其与新属性合并:
function test (obj, bloodtype) {
return {...obj, bloodtype};
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.