问题描述
谁能解释一下这行代码是如何工作的.
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
创建一个新数组,然后获取与 pushhref="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/push" rel="noreferrer">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.apply 或 Function.bind
设置 this
如果你想使用任意函数作为方法工作.
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(arrArguments[0], arrArguments[1], ..., arrArguments[n])
如果 thisObject
中有 push
原型链.由于 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 中,您可以简单地使用 spread 语法 与
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 如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!