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

查看:24
本文介绍了[].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 创建一个新数组,然后获取与 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.applyFunction.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 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 是因为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 如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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