根據api返回做篩檢判斷

需求是如果api返回符合 '万', '千', '百', '十', '个' 

就在對應位置顯示 √ 不然就顯示 - 

舊有寫法:

var arr = ['万', '千', '百', '十', '个'], result = []; for (var index in arr) { result.push(data.code_position.indexOf(arr[index]) != -1 ? '√' : '-'); }

 代碼優化後:

const arr = ['万', '千', '百', '十', '个']; const result = arr.map(item => data.code_position.includes(item) ? '√' : '-');

api回吐  万,,十,

顯示結果 √ ,-,-,√ ,-

依此類推 

優化說明:

  1. 使用 const 代替 var 宣告變數,避免變數被重新賦值造成錯誤。

  2. 使用 Array.prototype.map() 方法,取代 for...in 循環,使代碼更加簡潔易讀。

  3. 使用 Array.prototype.includes() 方法,取代 indexOf() 方法,使代碼更加簡潔易讀。

  4. 更改變數命名,讓變數名稱更加具有表達意義。  

留言

熱門文章