js字符串和数组互相转换
2021-10-15 16:54:48 来源:admin 点击:585
1、字符串转换为数组
var string = '123,456,789';
var stringResult = string.split(',');
console.log(stringResult) //输出["123", "456", "789"]
var string2 = 'abcdef'
var string2Result = string2.split('')
console.log(string2Result) //输出['a','b','c','d','e','f']
string2.split(",").map(Number);//输出[123,456,789]
JSON.parse("[" + string + "]"); //输出[123,456,789]
2、数组转换为字符串
var array = ['abc', 'def', 'hig']
var arrayResult = array.join(',')
console.log(arrayResult) // 输出"abc,def,hig"
array.toString()//输出"abc,def,hig"