前端JS字符串数组数字数组相互转换

字符串数组转化数字数组

let values = ['0', '1', '5', '10', '15', '2'];
let valueArr = values.map((item) => { 
	return Number(item);
});
console.log(valueArr);   //[0, 1, 5, 10, 15]

数字数组转化为字符串数组

let strArr = valueArr.map((item) => { 
	return String(item);
});
console.log(strArr); //["0", "1", "5", "10", "15"]

sort实现排序(无须将字符串数组转化为数字数字也可实现正常排序)

      let values = ['0', '1', '5', '2', '10', '15'];
      let values2 = [0, 1, 5, 2, 10, 15];
      function compare(value1, value2) { 
        return value1 - value2;
      }
      //正序排序
      values.sort(compare);
      console.log(values); // ["0", "1", "2", "5", "10", "15"]
      values2.sort(compare); 
      console.log(values2); // [0, 1, 2, 5, 10, 15]
      // 逆序排序
      function reverseCompare(value1, value2) { 
        return value2 - value1;
      }
      values.sort(reverseCompare);
      console.log(values); //["15", "10", "5", "2", "1", "0"]
      values2.sort(reverseCompare);
      console.log(values2); // [15, 10, 5, 2, 1, 0]
    原文作者:wingchiehpih
    原文地址: https://blog.csdn.net/wingchiehpih/article/details/108416603
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞