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]

发布了302 篇原创文章 · 获赞 250 · 访问量 172万+

猜你喜欢

转载自blog.csdn.net/qq_35624642/article/details/103153686
今日推荐