为什么[array] .concat()和[array] .concat.apply()提供不同的输出?

Rah*_*ran 7 javascript

下面的代码,

console.log([].concat.apply([2],[[99],5,6,[2,3]]));
Run Code Online (Sandbox Code Playgroud)

输出

[ 2, 99, 5, 6, 2, 3 ]
Run Code Online (Sandbox Code Playgroud)

还有下面的代码

console.log([2].concat([99]).concat([5,6,[2,3]]));
Run Code Online (Sandbox Code Playgroud)

输出

[ 2, 99, 5, 6, [ 2, 3 ] ]
Run Code Online (Sandbox Code Playgroud)

我的假设是

console.log([].concat.apply([2],[[99],5,6,[2,3]]));
Run Code Online (Sandbox Code Playgroud)

应该

[2,[99],5,6,[2,3]]
Run Code Online (Sandbox Code Playgroud)

但是,为什么呢?

Ale*_*ara 6

那是因为:

console.log( [].concat.apply([2],[[99],5,6,[2,3]]) );
Run Code Online (Sandbox Code Playgroud)

等效于:

console.log( [2].concat([99], 5, 6, [2,3]) );
Run Code Online (Sandbox Code Playgroud)

.concat接受多个参数,然后将所有数组(和非数组参数)合并到一个数组中。基本上,数组参数将解压缩为1级。

要获得该输出,您必须将每个数组元素包装在另一个数组中。

console.log( [].concat.apply([2],[[[99]],5,6,[[2,3]]]) );
Run Code Online (Sandbox Code Playgroud)

也许您更喜欢使用.push基于基础的方法。

console.log( [].concat.apply([2],[[99],5,6,[2,3]]) );
Run Code Online (Sandbox Code Playgroud)


Raj*_*amy 5

您在某种程度上没有看到文档就做出了假设。看, concat 的实际语法是,

\n\n
Array.prototype.concat ( [ item1 [ , item2 [ , \xe2\x80\xa6 ] ] ] )\n
Run Code Online (Sandbox Code Playgroud)\n\n

所以你的代码几乎等于,

\n\n
[].concat.apply([itm1], [itm2,itm3,itm4]...)\n
Run Code Online (Sandbox Code Playgroud)\n\n

从您的代码的角度来看,您的代码类似于,

\n\n
[2].concat([99],5,6,[2,3]);\n
Run Code Online (Sandbox Code Playgroud)\n\n

让我们拆除你的代码,

\n\n
console.log([].concat.apply([2],[[99],5,6,[2,3]]));\n// 1. apply will call the function by applying the parameter supplied as an array.\n// 2. so the first parameter for apply would be this for that function\n// 3. and the second parameter for it would be the arguments in an array form.\n// 4. Hence internally apply will call the function concat as,\n//    [2].concat([99],5,6,[2,3]); //[2] will be \'this\'\n
Run Code Online (Sandbox Code Playgroud)\n\n

但对于您的要求,您不需要使用apply,您可以使用call.

\n\n
console.log([].concat.call([2],[[99],5,6,[2,3]]));\n//[2,[99],5,6,[2,3]]\n
Run Code Online (Sandbox Code Playgroud)\n