1 javascript variables constants node.js
当我尝试这段代码时,我无法为对象中的“option_code”赋予 const。
const option_code = "option1211";
const product_code = "3344";
const size_code = "44"
var product_data = {
option_code: size_code,
quantity: "1",
product_id: product_code,
}
Run Code Online (Sandbox Code Playgroud)
我想要这样的结果(选项代码需要更改)=>
{ option1211:'44', quantity:'1', product_id:'3344' }
Run Code Online (Sandbox Code Playgroud)
这可能吗 ?
已经很接近了,您只需在键名称周围添加方括号即可:
var product_data = {
[option_code]: size_code,
quantity: "1",
product_id: product_code,
}
Run Code Online (Sandbox Code Playgroud)
否则,您可以执行以下操作:
var product_data = {
quantity: "1",
product_id: product_code,
}
product_data[option_code] = size_code;
Run Code Online (Sandbox Code Playgroud)