[] .push.apply如何工作? [英] How does the [].push.apply work?

查看:71
本文介绍了[] .push.apply如何工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以解释一下这行代码如何工作吗?

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,它与

[].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 have Array.prototype.push.apply(thisObject, arrArguments) is the same as thisObject.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的使用是因为pushpermutations数组的所有内容作为参数.因此,如果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如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆