Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/csharp-4.0/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript Stringfy将方法替换为数组的函数_Javascript_Json - Fatal编程技术网

Javascript Stringfy将方法替换为数组的函数

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 }

我仍在学习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"]
资料来源:
现在我没有得到的部分是replace2的函数参数,它是I和val。我得到了I应该是索引,val是ar(如果我在这里错了,请纠正我)。但是函数如何知道这一点呢?它如何区分指数和ar值

它不是
索引

首先要了解这个
数组也是一个对象。使用键0,1,2。。。。我们假设它是索引

在函数中,两个参数是对象的
。如果对以下对象执行
JSON.stringify

{
   foo: 'a',
   bar: 'b'
}
您将在第一次迭代中获得参数
'foo',a'
,在第二次迭代中获得参数
'bar',b'

希望我说得清楚。

这就是替代品,“它需要两个参数:键和正在字符串化的值。”