在平时的开发当中,我们都会拿到后端的数据,然后转换为我们前端需要的数据格式,下面我就来说一下字符串和数组之间的转换吧,是为了记录一下,方便日后查看,也希望能给一些不太熟悉这方面的小伙伴们一些帮助。
1.数组转换为字符串
let array = [1,2,3,4,5,6] let array2 = array.join(',') let array3 = array.toString()
console.log(array2, typeof array2)//> 1,2,3,4,5,6,string console.log(array3,typeof array3)//> 1,2,3,4,5,6,string console.log(array, typeof array)//> [1,2,3,4,5,6],object
2.字符串转换为数组
let string1 = '1,2,3,4,5,6' let string2 = string1.split(',') console.log(string2, typeof string2)//> ["1","2","3","4","5","6"],object console.log(string1,typeof string1)//> 1,2,3,4,5,6,string
3.字符串转换为数组,并且数组中的每个元素也是数字类型
let string4 = string1.split(',').map(Number) console.log(string4) //> [1,2,3,4,5,6]
let string5 = JSON.parse("[" + string1 + "]") console.log(string5)>//> [1,2,3,4,5,6]