js数组,字符串,json互相转换函数有哪些

时间:2023-12-09 23:22:19

js数组,字符串,json互相转换函数有哪些

一、总结

一句话总结:

JSON.stringify(arr) JSON.parse(jsonString)
str.split('')
array.join('')

1、js数组如何转字符串?

array.join('')
var arr = [1,2,3,4,'巴德','merge'];
var str = arr.join(',');
console.log(str); // 1,2,3,4,巴德,merge

2、字符串如何转数组?

str.split('')
var str = '1,2,3,4,巴德,merge';
var arr = str.split(',');
console.log(arr); // ["1", "2", "3", "4", "巴德", "merge"] 数组
console.log(arr[4]); // 巴德

3、js数组转json字符串和json字符串转数组?

JSON.stringify(arr) JSON.parse(jsonString)
var str = '1,2,3,4,巴德,merge';
var arr = str.split(',');
var strify = JSON.stringify(arr);
console.log(arr); // ["1", "2", "3", "4", "巴德", "merge"] 数组
console.log(arr[4]); // 巴德
console.log(strify); // ["1", "2", "3", "4", "巴德", "merge"] 字符串 var arrParse = JSON.parse(strify);
console.log(arrParse); // ["1", "2", "3", "4", "巴德", "merge"] 数组

二、js 数组,字符串,json互相转换(转)

转自:js 数组,字符串,json互相转换
https://www.cnblogs.com/woodk/p/5714329.html

数组转字符串

var arr = [1,2,3,4,'巴德','merge'];
var str = arr.join(',');
console.log(str); // 1,2,3,4,巴德,merge

字符串转数组

var str = '1,2,3,4,巴德,merge';
var arr = str.split(',');
console.log(arr); // ["1", "2", "3", "4", "巴德", "merge"] 数组
console.log(arr[4]); // 巴德

字符串转数组,数组转数组格式化,数组格式化转数组

var str = '1,2,3,4,巴德,merge';
var arr = str.split(',');
var strify = JSON.stringify(arr);
console.log(arr); // ["1", "2", "3", "4", "巴德", "merge"] 数组
console.log(arr[4]); // 巴德
console.log(strify); // ["1", "2", "3", "4", "巴德", "merge"] 字符串 var arrParse = JSON.parse(strify);
console.log(arrParse); // ["1", "2", "3", "4", "巴德", "merge"] 数组