[英]JSON.Stringfy method's replacer argument not working on nested object
[英]Json.Stringfy replace method with function to array
我仍在学习 javascript,最近我在互联网上偶然发现了这段代码,解释了 JSON.stringify 替换为数组:
var ar = ['one', 'two', 'three'];
function replacer2(i, val) {
if ( i === '0' ) { // identity operator and index in quotes
return undefined; // attempt to remove from result
} else if ( i == 1 ) { // equality operator and numeric version of index
return 2;
} else {
return val; // return unchanged
}
}
var json = JSON.stringify(ar, replacer2);
console.log(json);
// [null,2,"three"]
来源: https://www.dyn-web.com/tutorials/php-js/json/filter.php现在我没有得到的部分是替换的 ZC1C425268E68385D 和 14AB5074C17A9 的参数。 我知道我应该是索引,而 val 是 ar(如果我在这里错了,请纠正我)。 但是 function 怎么知道呢? 它如何区分索引和 ar 的值?
它不是index
和value
首先了解这个Array is also an object
。 使用键 0,1,2.... 我们假设为索引。
在您的 function 中,两个参数是 object 的key
和value
。 如果您按照JSON.stringify
执行 JSON.stringify
{
foo: 'a',
bar: 'b'
}
您将在第一次迭代中获得参数为'foo', 'a'
,在第二次迭代中获得'bar', 'b'
。
希望我清楚。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.