gpt4 book ai didi

javascript - 为什么 JSON.stringify() 在传递替换函数时返回未定义?

转载 作者:行者123 更新时间:2023-11-29 19:37:09 26 4
gpt4 key购买 nike

当我将一个函数作为第二个参数传递给 JSON.stringify() 并测试键的值时,我得到了 undefined。知道为什么吗?

var person = {
name: "Siddharth",
age: 23,
sex: 0,
phone: 12345
};

personString = JSON.stringify(person, personFilter, 2);
console.log(personString);

function personFilter(key, value) {
if (key == "age") {
return value;
}
}

fiddle

最佳答案

如果你只想得到“年龄”,你可以使用数组而不是函数:

personString = JSON.stringify(person, ["age"], 2);

If you use a function, it is getting the whole object first

The replacer parameter can be either a function or an array. As a function, it takes two parameters, the key and the value being stringified. The object in which the key was found is provided as the replacer's this 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. It should return the value that should be added to the JSON string, as follows:

  • If you return a Number, the string corresponding to that number is used as the value for the property when added to the JSON string. If you return a String, that string is used as the property's value when adding it to the JSON string.

  • If you return a Boolean, "true" or "false" is used as the property's value, as appropriate, when adding it to the JSON string.

  • If you return any other object, the object is recursively stringified into the JSON string, calling the replacer function on each property, unless the object is a function, in which case nothing is added to the JSON string.

  • If you return undefined, the property is not included in the output JSON string.

至于为什么整个对象的键是空的……这真的是唯一的选择——任何其他的都可以作为对象属性的键,空键是只有他们可以使用的东西,然后你才能知道 - 在转换器函数中 - “这绝对是整个对象”,无论对象包含什么。

所以在你的情况下,它看起来像:

personString = JSON.stringify(person, personFilter, 2);

function personFilter(key, value) {
if (key == "age" || key == "") {
return value;
}
}

关于javascript - 为什么 JSON.stringify() 在传递替换函数时返回未定义?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24809428/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com