gpt4 book ai didi

javascript - 如何使用变量访问键/值对?

转载 作者:行者123 更新时间:2023-12-02 22:18:25 24 4
gpt4 key购买 nike

我希望使用变量动态访问键/值对。我可以使用 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

代码笔:https://codepen.io/m-use/pen/XWJKBMB

最佳答案

这应该可以解决问题

topics[topic].color

let topic = 'social';

const topics = {
social: {
color: 'red'
},
emotional: {
color: 'blue'
},
physical: {
color: 'green'
}
};

console.log(topics[topic].color);

Further Info

关于javascript - 如何使用变量访问键/值对?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59312856/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com