function addPropertyToProduct(product, property, value) {
let tryThis = property;
product.tryThis = value;
return product;
}
Run Code Online (Sandbox Code Playgroud)
参数“product”将是一个如下所示的对象:
{ type: 'Terminator 2: Judgement Day', price: '£6.99', quantity: 1 }
Run Code Online (Sandbox Code Playgroud)
给定一个“属性”作为参数,以及它的相应值,更新“产品”以包含这个新信息。然后返回更新的“产品”。
例如,如果给定 'property' 'length' 和值 '2h 36m',你的函数应该返回
{ type: 'Terminator 2: Judgement Day', price: '£6.99', quantity: 1, length: '2h 36m' }
Run Code Online (Sandbox Code Playgroud)
这是我收到的答案:
**+ expected** *- actual*
{
**+ "length": "2h 36m"**
"price": "£6.99"
"quantity": 1
*- "tryThis": "2h 36m"*
"type": "Terminator 2: Judgement Day"
}
Run Code Online (Sandbox Code Playgroud)
这会正确返回值,但将键命名为变量名,而不是参数本身?
使用方括号[]:
function addPropertyToProduct(product, property, value) {
let tryThis = property;
product[tryThis] = value;
return product;
}
Run Code Online (Sandbox Code Playgroud)
有关更多信息,请查看:MDN 计算属性名称