JSON.stringify(value[, replacer[, space]])
1. JSON.stringify(value[, replacer[, space]]);
value 必需 对象或数组,需要转换成json字符串的数据
replacer 可选 函数或数组
space 可选 文本添加缩进、空格和换行符,小于等于10的数字(如大于10按10展示)或者是代表缩进、空格和换行符的转义字符,例如'\t'
2.举栗子
1)仅有第一个参数
let obj = { name: 'LQW', age: 23, sex: 'female' }; console.log(JSON.stringify(obj)); 结果: {"name":"LQW","age":23,"sex":"female"}
2)传入第三个参数
let obj = { name: 'LQW', age: 23, sex: 'female' }; console.log(JSON.stringify(obj, null, 4)); 结果: { "name": "LQW", "age": 23, "sex": "female" }
3)第一个参数为数组,第二个参数为函数
let arr = ['Lqw', 23, 'female']; console.log(JSON.stringify(arr, function (key, value) { if (typeof value === 'string') { return value.toUpperCase(); } return value; }, 4)); 结果: [ "LQW", 23, "FEMALE" ]
4)第一个参数为数组,第二个参数为数组,第二个参数会被忽略
let arr = ['Lqw', 23, 'female']; console.log(JSON.stringify(arr, [1, 2], 4)); 结果: [ "Lqw", 23, "female" ]
5)第一个参数为对象,第二个参数为数组
let obj = { name: 'LQW', age: 23, sex: 'female' }; console.log(JSON.stringify(obj, ['name', 'sex'], 4)); 结果: { "name": "LQW", "sex": "female" }
let obj = { name: 'LQW', age: 23, sex: 'female' }; console.log(JSON.stringify(obj, ['1', '2'], 4)); 结果: {}
6)第一个参数为对象,第二个参数为函数
let obj = { name: 'LQW', age: 23, sex: 'female' }; console.log(JSON.stringify(obj, function (key, value) { if (typeof value === 'string') { return value.toUpperCase(); } return value; }, 4)); 结果: { "name": "LQW", "age": 23, "sex": "FEMALE" }