js中数组、对象和字符串之间的相互转化
1. 字符串转化为数组:split()方法
split()方法将字符串按某个字符切割成若干个字符串,并以数组形式返回
// 实例:输出今天是星期几
var str = '星期日,星期一,星期二,星期三,星期四,星期五,星期六';
var today = new Date();
var day = today.getDay();
console.log(day); //5
var arr = str.split(','); //按','分割
console.log(arr); //[星期日,星期一,星期二,星期三,星期四,星期五,星期六]
console.log("今天是:" + arr[day]);
2. json字符串转为对象: JSON.parse()
const str = '{"id": 0,"name": "dd","age": 12}'
const strToObj = JSON.parse(stg)
console.log('str:', str)//{"id": 0,"name": "dd","age": 12}
console.log('strToObj:', strToObj)//{id: 0, name: 'dd', age: 12}
3. 数组转化为字符串:
join()方法
join()方法将数组元素用某个字符连接成字符串
var arr = ['a', 'b', 'c', 'd'];
var str1 = arr.join('-');
console.log(typeof(str1)); //string
console.log(str1); //a-b-c-d
toString()方法
toString()方法将数组元素以 ’ , ’ 分隔合并为字符串
var arr1 = [1, 'a', 3, 4];
var str2 = arr1.toString();
console.log(typeof(str2)); //string
console.log(str2); //1,a,3,4
4. 数组转化为对象
let arr2 = [{
name: 'dr',
ct: 'dr001'
},
{
name: 'ljy',
ct: 'ljy002'
}
]
let obj = {}
arr2.forEach((item, index) => {
//forEach() 方法对数组的每个元素执行一次提供的函数,item数组元素,index数组索引
obj[item.name] = item.ct
})
console.log(obj); //{dr: 'dr001', ljy: 'ljy002'}
5.对象转化为数组
6.对象转化为字符串 JSON.stringify()
const obj1 = {
id: 0,
name: 'dd',
age: 12
}
const objToStr = JSON.stringify(obj1)
console.log('obj:', obj1)//{id: 0, name: 'dd', age: 12}
console.log('objToStr:', objToStr)//{"id":0,"name":"dd","age":12}
console.log(typeof objToStr)//string