简体   繁体   English

将数组和其他参数传递给函数。 怎么样?

[英]Pass an array and further arguments into a function. How?

I have a function which takes an array and further arguments like this: function arrayandmore([1, 2, 3], 2, 3) I need to return the array ([1, 2, 3]) without those elements which equals the arguments coming behind the array. 我有一个函数,它接受一个数组和其他参数,如下所示:function arrayandmore([1,2,3],2,3)我需要返回数组([1,2,3]),而不需要那些等于数组后面的参数。 So in this case, the returned array would be: ([1]). 所以在这种情况下,返回的数组将是:([1])。

One of my approaches is: 我的一种方法是:

function destroyer(arr) {
  var args = Array.from(arguments);
  var i = 0;
  while (i < args.length) {
    var result = args[0].filter(word => word !== args[i]);
    i++;
  }
  console.log(result);
}

destroyer([1, 1, 3, 4], 1, 3);

Console returns: 控制台返回:

[ 1, 1, 4 ]

I don't understand, why it returns one too - I don't understand, why it does not work. 我不明白,为什么它也会返回 - 我不明白,为什么它不起作用。

It is the same with using splice. 使用拼接也是一样的。

function destroyer(arr) {
  var args = Array.from(arguments);
  var quant = args.length - 1;
  for (var i = 1; i <= quant; i++) {
    if (arr.indexOf(args[i]) !== -1) {
      arr = arr.splice(arr.indexOf(args[i]));
    }
    console.log(arr);
  }
}
destroyer([1, 1, 3, 4], 1, 3); 

I think, both ways should work. 我认为,两种方式都应该有效。 But I don't figure out why they don't. 但我不明白他们为什么不这样做。

Your while won't work because result is being overwritten in every loop. 你的while不会起作用,因为每个循环都会覆盖result So, it only ever removes the last parameter to the destroyer function 因此,它只会删除destroyer功能的最后一个参数

You can use the rest parameter syntax to separate the array and the items to be removed. 您可以使用rest参数语法来分隔数组和要删除的项。

Then use filter and includes like this: 然后使用filterincludes如下:

 function destroyer(arr, ...toRemove) { return arr.filter(a => !toRemove.includes(a)) } console.log(destroyer([1, 1, 3, 4, 5], 1, 3)) 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM