gpt4 book ai didi

javascript - 将函数传递给 JSON.stringify

转载 作者:行者123 更新时间:2023-11-28 17:51:54 24 4
gpt4 key购买 nike

我目前正在通过“你不懂js”系列学习javascript。

在“类型和语法”一节中,在讨论“JSON.stringify”函数时,作者提到了

var a = {
b: 42,
c: "42",
d: [11,22,33]
};

JSON.stringify( a, ["b","c"] ); // "{"b":42,"c":"42"}"

JSON.stringify( a, function(k,v){
if (k !== "c") return v;
} );
// "{"b":42,"d":[11,22,33]}"

Note: In the function replacer case, the key argument k is undefined for the first call (where the a object itself is being passed in). The if statement filters out the property named "c". Stringification is recursive, so the [1,2,3] array has each of its values (1, 2, and 3) passed as v to replacer, with indexes (0, 1, and 2) as k.

所以我想出了以下代码,旨在从 JSON.stringify 结果中删除值 22

var a = {
b: 42,
c: "42",
d: [11, 22, 33]
};

var result = JSON.stringify(a, function(k, v) {
//since each index 0, 1, 2 of property "c" will be passed into function as "k",
//therefore if "k !== 1" should filter out value 22
if (k !== 1) {
return v;
}
});

console.log(result);

我期望结果为 "{"b":42,"c":"42","d":[11,33]}"

但是,结果却是 "{"b":42,"c":"42","d":[11,22,33]}" (如您所见,属性c的索引1处的值22没有被过滤掉)

我是不是没理解作者说的意思?我错过了什么吗?

最佳答案

属性名称始终是字符串。 1 !== "1"。与字符串而不是数字进行比较。

var a = {
b: 42,
c: "42",
d: [11, 22, 33]
};

var result = JSON.stringify(a, function(k, v) {
if (k !== "1") { // "1" not 1 here
return v;
}
});

console.log(result);

关于javascript - 将函数传递给 JSON.stringify,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45329551/

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