最常用:JSON.stringify將對象/數(shù)組轉換成字符串;JSON.parse將字符串轉成json對象,
當他倆配合起來,一起作用在一個變量上時,是深拷貝的功能。文章來源:http://www.zghlxwxcb.cn/news/detail-526697.html
JSON.parse
JSON.parse 是有兩個參數(shù)的,第一個必填,另一個可選函數(shù)文章來源地址http://www.zghlxwxcb.cn/news/detail-526697.html
let str = '{"isSHow":true, "age":18}'
const obj = JSON.parse(str,function(key,val){
if((typeof val) == 'number') return val * 2
return val
});
console.log(obj);//{isSHow: true, age: 36}
JSON.stringify
- JSON.stringify 是有三個參數(shù),第一個必填,其他倆可選
- 第一個就是對象,
- 第二個replacer 函數(shù),選擇性地僅處理包含數(shù)組指定的屬性(可以是數(shù)組 也可以是方法);
- 第三個是用來控制字符間距;如為數(shù)字,縮進數(shù)字個字符(最大長度10);如為轉義字符(比如是\t 回車,每行就有一個回車);如為字符串,每行輸出的時候把這些字符串加上(最大長度10)
const settings = {
username: "jiajia",
level: 171,
health: 60
};
const data = JSON.stringify(settings, ["health",'level'],' '); //有空格間距
console.log(data);
//{
// "health": 90
// }
// const data = JSON.stringify(settings, ["health"],'');//第三個參數(shù)不加和現(xiàn)在會是一樣的結果
// console.log(data);{"health": 90}
到了這里,關于JSON.stringify()和JSON.parse()那些你不知道的參數(shù)的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關文章,希望大家以后多多支持TOY模板網(wǎng)!