This question already has answers here:
How to use a variable for a key in a JavaScript object literal?
(16个答案)
Creating object with dynamic keys [duplicate]
(2个答案)
2年前关闭。
我正在运行此代码,但给出的结果很奇怪?
预期输出:
实际输出:
(16个答案)
Creating object with dynamic keys [duplicate]
(2个答案)
2年前关闭。
我正在运行此代码,但给出的结果很奇怪?
let surveyTypes = [1,2];
let surveyDuration = {
surveyTypes[0]: 'first',surveyTypes[1]: 'second'
}
预期输出:
surveyDuration={1:'first',2:'second'}
实际输出:
最佳答案
因为要创建wrap
键,所以必须将数组的项目dynamic
放在方括号中。
let surveyTypes = [1,2];
let surveyDuration = {
[surveyTypes[0]]: 'first',[surveyTypes[1]]: 'second'
}
console.log(surveyDuration);
09-17 23:15