Javascript Stringfy将方法替换为数组的函数
我仍在学习javascript,最近我在互联网上偶然发现了这段解释JSON.stringify替换为数组的代码:Javascript Stringfy将方法替换为数组的函数,javascript,json,Javascript,Json,我仍在学习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 }
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"]
资料来源:
现在我没有得到的部分是replace2的函数参数,它是I和val。我得到了I应该是索引,val是ar(如果我在这里错了,请纠正我)。但是函数如何知道这一点呢?它如何区分指数和ar值 它不是
索引
和值
首先要了解这个数组也是一个对象。使用键0,1,2。。。。我们假设它是索引
在函数中,两个参数是对象的键
和值
。如果对以下对象执行JSON.stringify
{
foo: 'a',
bar: 'b'
}
您将在第一次迭代中获得参数'foo',a'
,在第二次迭代中获得参数'bar',b'
希望我说得清楚。这就是替代品,“它需要两个参数:键和正在字符串化的值。”