function addPropertyToProduct(product, property, value) {
let tryThis = property;
product.tryThis = value;
return product;
}
参数“product”将是一个如下所示的对象:
{ type: 'Terminator 2: Judgement Day', price: '£6.99', quantity: 1 }
给定“属性”作为参数及其对应值,更新“产品”以包含此新信息。然后返回更新后的“产品”。
例如如果给出“属性”“长度”和值“2h 36m”,你的函数应该返回
{ type: 'Terminator 2: Judgement Day', price: '£6.99', quantity: 1, length: '2h 36m' }
这是我收到的答案:
**+ expected** *- actual*
{
**+ "length": "2h 36m"**
"price": "£6.99"
"quantity": 1
*- "tryThis": "2h 36m"*
"type": "Terminator 2: Judgement Day"
}
这会正确返回值,但将键命名为变量名,而不是参数本身?
最佳答案
使用方括号[]
:
function addPropertyToProduct(product, property, value) {
let tryThis = property;
product[tryThis] = value;
return product;
}
有关更多信息,请查看:MDN Computed Property Names
关于javascript - 如何通过参数添加对象属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59918241/