数值数组与字符串数组转换

2022/8/30 23:24:13

本文主要是介绍数值数组与字符串数组转换,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

数值数组转字符串数组

方法一:
var arr1 = [1, 2, 5];
arr1 = arr1.map(String);  //将arr1转换为字符串数组
console.log(arr1);//结果: ["1","2","5"]

方法二:
var arr1 = [1, 2, 5];
arr1 = arr1.toString(); //将arr1转换为字符串,结果为:"1,2,5"
arr1=arr1.split(",");//将arr1转换为数组,分隔符为",",结果为["1", "2", "5"]

字符串数组转数值数组

方法一:
var arr1 = ["1","2","5"];
arr1 = arr1.map(Number);  //将arr1转换为数值数组
console.log(arr1);//结果: [1,2,5]

方法二:
var arr1 = ["1","2","5"];
for(let i=0;i<arr1.length;i++){
    arr1[i] = parseInt(arr1[i])
}        
console.log(arr1);// 结果为:[1,2,5]

 



这篇关于数值数组与字符串数组转换的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程