js字符串數組轉數字數組,並去掉最後一個元素

js把字符串數組轉數字數組

let menuIds=["1,2,3","3,6,7,4,2"2,5,3"]//測試數據
let newArr = [];//初始化數組
if (Array.isArray(menuIds)) {
      for (let o of menuIds) {//循環數組
         let menuId = o.split(",").map(Number);//用分割函數把字符串分割成字符數組,再用map函數轉化爲數字數組
         newArr.push(menuId);
      }
}
let newMenuIds = newArr;

其他方法舉例:

['1','2','3'] => [1,2,3]

['1','2','3'].map(Number) // [1,2,3]

['1','2','3'].map((value)=>{ return parseInt(value) }) // [1,2,3]

JSON.parse('[' + String(['1', '2', '3']) + ']') // [1,2,3] 

eval('[' + String(['1', '2', '3']) + ']') // [1,2,3]

發佈了303 篇原創文章 · 獲贊 256 · 訪問量 175萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章