问题描述
有人可以解释一下这行代码如何工作吗?
can someone please explain me how does this line of code work.
[].push.apply(perms, permutation(arr.slice(0), start + 1, last));
此函数生成输入数组的所有排列的数组;
This function generates an array of all permutations of an input array;
var permutation = function(arr, start, last){
var length = arr.length;
if(!start){
start = 0;
}
if(!last){
last = length - 1;
}
if( last === start){
return [arr];
}
var temp;
var perms = [];
for(var i = start; i < length; i++){
swapIndex(arr, i, start);
console.log(arr);
[].push.apply(perms, permutation(arr.slice(0), start + 1, last));
swapIndex(arr, i, start);
}
return perms;
};
推荐答案
[].push
创建一个新数组,然后获取push
,它与 Array.prototype.push
,但每次需要进行垃圾收集时都会创建未使用的对象.
[].push
creates a new array, then fetches push
which is the same as Array.prototype.push
but with creating an unused object each time that needs to be garbage collected.
如果调用Array.prototype.push(5)
,它将不会起作用,因为不会将this
设置为数组或扩展数组的内容.因此,您需要使用 Function.call
, Function.apply
或 Function.bind
设置如果要使用任意函数作为方法.
If you call Array.prototype.push(5)
it wont work since this
wouldn't be set to an array or something that extends an array. Thus you need to use either Function.call
, Function.apply
or Function.bind
to set this
if you want to use an arbitrary function to work as a method.
如果有Array.prototype.push.apply(thisObject, arrArguments)
与如果thisObject
在其原型链中具有push
,则为thisObject.push(arrArguments[0], arrArguments[1], ..., arrArguments[n])
.由于perms
是一个数组,并且在其自己的原型链中具有push
,因此可以替换为:
If you haveArray.prototype.push.apply(thisObject, arrArguments)
is the same asthisObject.push(arrArguments[0], arrArguments[1], ..., arrArguments[n])
if thisObject
has push
in its prototype chain. Since perms
is an array and has push
in it's own prototype chain it could be replaced with:
perms.push.apply(perms, permutation(arr.slice(0), start + 1, last));
apply
的使用是因为push
将permutations
数组的所有内容作为参数.因此,如果permutations(....)
返回[1,2,3]
,它将与perms.push(1, 2, 3)
同义.您可以通过为每个元素调用push
来编写不带apply
的代码:
The use of apply
is because push
gets all the contents of the permutations
array as arguments. thus if permutations(....)
returned [1,2,3]
it would be synonymous with perms.push(1, 2, 3)
. You could write it without apply
by calling push
for each element:
for (var e of permutation(arr.slice(0), start + 1, last)) {
perms.push(e);
}
在ES6中,您可以简单地使用传播语法与apply
相同,但更易于理解:
And in ES6 you can simply use the spread syntax which is the same as apply
but simpler to comprehend:
perms.push(...permutation(arr.slice(0), start + 1, last))
这篇关于[] .push.apply如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!