簡體   English   中英

反應:創建和使用動態變量

[英]react: Create and use dynamic variables

我有一個列表/數組cities = ["Bangalore", "Delhi", "Hyderabad", "Mumbai", "Chennai"] 我需要動態變量,例如[city]Weather[city]Temperature等。例如:我也需要BangaloreWeather,DelhiWeather,HyderabadWeather,MumbaiWeather,ChennaiWeather和類似的溫度。

我嘗試使用1) ${city}Weather ,但是由於“復雜的綁定模式需要初始化值”而出現錯誤,2) city+"Weather"請幫我解決問題。謝謝!

使用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
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM