Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/14.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:使用concat和reduce进行练习_Javascript_Arrays - Fatal编程技术网

Javascript:使用concat和reduce进行练习

Javascript:使用concat和reduce进行练习,javascript,arrays,Javascript,Arrays,我正在做一个练习,从一个数组开始,我必须在一个数组中减少它(使用reduce和concat),该数组包含给定的每个数组的所有元素 所以我从这里开始: var array = [[1,2,3],[4,5,6],[7,8,9]] 我用这个解决了这个问题: var new_array = array.reduce(function(prev,cur){return prev.concat(cur);}) 所以它可以工作,输入console.log(新的数组)我有: [1, 2, 3, 4, 5,

我正在做一个练习,从一个数组开始,我必须在一个数组中减少它(使用reduce和concat),该数组包含给定的每个数组的所有元素

所以我从这里开始:

var array = [[1,2,3],[4,5,6],[7,8,9]]
我用这个解决了这个问题:

var new_array = array.reduce(function(prev,cur){return prev.concat(cur);})
所以它可以工作,输入
console.log(新的数组)
我有:

[1, 2, 3, 4, 5, 6, 7, 8, 9]
但如果我以这种方式修改函数:

var new_array = array.reduce(function(prev,cur){return prev.concat(cur);},0)
我得到这个错误:

“TypeError:prev.concat不是函数

为什么我会犯这个错误

我还不完全清楚reduce是如何工作的

它的工作原理如下:

Array.prototype.reduce = function(callback, startValue){
    var initialized = arguments.length > 1,
        accumulatedValue = startValue;

    for(var i=0; i<this.length; ++i){
        if(i in this){
            if(initialized){
                accumulatedValue = callback(accumulatedValue, this[i], i, this);
            }else{
                initialized = true;
                accumulatedValue = this[i];
            }
        }
    }

    if(!initialized)
        throw new TypeError("reduce of empty array with no initial value");
    return accumulatedValue;
}

0
替换为数组,如
[0]

,因为无法将数组压缩到0秒(可选)
Array.prototype.reduce
的参数是初始值。在您的情况下,您将
0
作为初始值传递,因此函数第一次运行时,它尝试调用
prev.concat
,这显然会失败,因为
Number
没有
concat
方法。您试图通过h第二个版本的reduce?多亏了大家,我还不完全清楚reduce是如何工作的
var array = [[1,2,3],[4,5,6],[7,8,9]];

var tmp = 0;
//and that's where it fails.
//because `tmp` is 0 and 0 has no `concat` method
tmp = tmp.concat(array[0]);
tmp = tmp.concat(array[1]);
tmp = tmp.concat(array[2]);

var new_array = tmp;