JSON.stringify的5种使用情况
- 前端
- 三生万物
- 0
const foo = {name: 'tom', age: 18}
// 第二个参数为null
console.log(JSON.stringify(foo, null)) // {"name":"tom","age":18}
// 第二个参数为数组
console.log(JSON.stringify(foo, ['name'])) // [{"name":"tom"}]
// 第二个参数为函数
console.log(JSON.stringify(foo, (key, value) => typeof value === "string" ? undefined : value)) // {"age":18}
// 第二个参数为null,第三个参数为数字(表示空格数量)
console.log(JSON.stringify(foo, null, 2))
/*
{
"name": "tom",
"age": 18
}
*/
// 第二个参数为null,第三个参数为字符串(表示前缀)
console.log(JSON.stringify(foo, null, '|--'))
/*
{
|--"name": "tom",
|--"age": 18
}
*/
注意:如果键值为 undefined
会被忽略
const foo = {name: 'tom', age: 18, gender: undefined}
console.log(JSON.stringify(foo)) // {"name":"tom","age":18}
免责申明:本站发布的内容(图片、视频和文字)以转载和分享为主,文章观点不代表本站立场,如涉及侵权请联系站长邮箱:xbc-online@qq.com进行反馈,一经查实,将立刻删除涉嫌侵权内容。