1)、 json.stringify()、json.parse()区别
JSON.stringify()将 JavaScript 对象转换为 JSON 字符串
let arr = [4,5,6];
JSON.stringify(arr);//'[4,5,6]'
typeof JSON.stringify(arr);//string
let string = '[4,5,6]';
console.log(JSON.parse(string))//[4,5,6]
console.log(typeof JSON.parse(string))//object
JSON.parse() 将 JSON 字符串转换为一个对象,键值都必须使用双引号包裹:
let a = '["6","7"]';
let b = "['6','7']";
console.log(JSON.parse(a));// Object [6,7]
console.log(JSON.parse(b));// 报错 synataxError:Unexpected token 'in JSON at position 1 at JSON.parse'
2)、让localStorage/sessionStorage可以存储对象。
localStorage/sessionStorage默认只能存储字符串,实际开发中,我们往往需要存储的数据多为对象类型,此时我们就可以在存储时利用JSON.stringify()将对象转为字符串,而在取缓存时,只需配合jJSON.parse()转回对象即可。
//存
function setLocalStorage(key,val){
window.localStorage.setItem(key,JSON.stringify(val));
};
//取
function getLocalStorage(key){
let val = JSON.parse(window.localStorage.getItem(key));
return val;
};
//测试
setLocalStorage('emo',[6,7,8]);
let a = getLocalStorage('emo');//[6,7,8]
3)、实现对象深拷贝
实际开发中,若是怕影响原数据(例:修改表单数据时,会发现修改同时页面中的数据跟着同时变动,此时需要使用深拷贝,不影响页面原数据,修改完点击确认后,页面数据才会更改),我们需深拷贝出一份数据做任意操作,直接使用JSON.stringify()与JSON.parse()来实现深拷贝;
function deepClone(data) {
//深拷贝
dataClone = JSON.parse(JSON.stringify(data));
return dataClone;
};
//测试
let arr = [1,2,3],
_arr = deepClone(arr);
arr[0] = 2;
console.log(arr,_arr)//[2,2,3] [1,2,3]
4)、JSON.stringify()与toString()的区别
两者都可以将目标值转为字符串,但本质上还是有区别的,比如
let arr = [1,2,3];
JSON.stringify(arr);//'[1,2,3]'
arr.toString();//1,2,3
JSON.stringify()的受众更多是对象;
toString()虽然可以将数组转为字符串,但并不能对{name:'张三'}这类对象实现想要的操作,它的受众更多是数字