如何使用变量访问 key/value 对?
How to access a key/value pair with a variable?
我希望使用 a 变量动态访问 key/value 对。我可以使用 topics.social.color
获得我正在寻找的值,但主题会根据用户的选择而改变。如何使用主题变量动态获取主题颜色?
let topic = 'social';
const topics = {
social: {
color: 'red'
},
emotional: {
color: 'blue'
},
physical: {
color: 'green'
}
};
console.log(topics.topic.color); // this does not work
这应该可以解决问题
topics[topic].color
let topic = 'social';
const topics = {
social: {
color: 'red'
},
emotional: {
color: 'blue'
},
physical: {
color: 'green'
}
};
console.log(topics[topic].color);
我希望使用 a 变量动态访问 key/value 对。我可以使用 topics.social.color
获得我正在寻找的值,但主题会根据用户的选择而改变。如何使用主题变量动态获取主题颜色?
let topic = 'social';
const topics = {
social: {
color: 'red'
},
emotional: {
color: 'blue'
},
physical: {
color: 'green'
}
};
console.log(topics.topic.color); // this does not work
这应该可以解决问题
topics[topic].color
let topic = 'social';
const topics = {
social: {
color: 'red'
},
emotional: {
color: 'blue'
},
physical: {
color: 'green'
}
};
console.log(topics[topic].color);