我正在使用 JSON.stringify 及其替换参数。但是在替换参数中我无法获取键和值,而不是我将键值作为空字符串“”并将值作为完整的 JSON 对象。我在我的代码中犯了什么错误?请清除它。
var replacer=function(key,value){
debugger;
}
$(function () {
JSON.stringify({"name":'xxxxx'},replacer)
});
我需要获取作为“name”的键和作为“xxxxx”的值
最佳答案
MDN - JSON.stringify(): The replacer parameter :
[...]Initially it gets called with an empty key representing the object being stringified, and it then gets called for each property on the object or array being stringified.[...]
在您的第一次迭代中,您将整个对象 {"name":'xxxxx'}
作为 value
,
但是因为您从替换函数返回了 undefined
,所以整个对象将被替换为 undefined
,因此下一次使用值/键对的迭代不会发生。
如果您返回 value
,您将看到下一次迭代发生。
var replacer = function(key, value) {
console.dir(arguments);
return value;
}
JSON.stringify({
"name1": 'xxxxx'
}, replacer);
关于javascript - JSON.Stringify 替换函数无法获取键值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36675980/