下面的代码,
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)
但是,为什么呢?
那是因为:
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)
您在某种程度上没有看到文档就做出了假设。看, concat 的实际语法是,
\n\nArray.prototype.concat ( [ item1 [ , item2 [ , \xe2\x80\xa6 ] ] ] )\nRun Code Online (Sandbox Code Playgroud)\n\n所以你的代码几乎等于,
\n\n[].concat.apply([itm1], [itm2,itm3,itm4]...)\nRun Code Online (Sandbox Code Playgroud)\n\n从您的代码的角度来看,您的代码类似于,
\n\n[2].concat([99],5,6,[2,3]);\nRun Code Online (Sandbox Code Playgroud)\n\n让我们拆除你的代码,
\n\nconsole.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\'\nRun Code Online (Sandbox Code Playgroud)\n\n但对于您的要求,您不需要使用apply,您可以使用call.
console.log([].concat.call([2],[[99],5,6,[2,3]]));\n//[2,[99],5,6,[2,3]]\nRun Code Online (Sandbox Code Playgroud)\n
| 归档时间: |
|
| 查看次数: |
2980 次 |
| 最近记录: |