我有一个列表/数组cities = ["Bangalore", "Delhi", "Hyderabad", "Mumbai", "Chennai"]
。我需要[city]Weather
,[city]Temperature
等动态变量。例如:我还需要BangaloreWeather,DelhiWeather,HyderabadWeather,MumbaiWeather,ChennaiWeather以及类似的温度指标。
我尝试使用
1)${city}Weather
,但出现错误,因为“复杂的绑定模式需要初始化值”,
2)city+"Weather"
请帮助我解决问题。谢谢!
答案 0 :(得分:0)
使用ES6,这可能有帮助?
const outcome = ["Bangalore", "Delhi", "Hyderabad", "Mumbai", "Chennai"].reduce((accumulator, currentValue) => {
accumulator[currentValue+"Weather"] = Math.random();
return accumulator;
},{});
OUTPUT:
{
"BangaloreWeather": 0.7831037919683015,
"DelhiWeather": 0.03695139822965743,
"HyderabadWeather": 0.10986926586742629,
"MumbaiWeather": 0.676334213130112,
"ChennaiWeather": 0.9095092973413457
}