简体   繁体   English

使用 function 从数组中删除多个元素

[英]Remove multiple elements from an array using a function

What I am trying to do is to return the [1, 4] array, however, I do not understand what's the mistake which ends up returning [1].我想要做的是返回 [1, 4] 数组,但是,我不明白最终返回 [1] 的错误是什么。 Any clues?有什么线索吗? Thank you!谢谢!

 const removeFromArray = function(arr) { for (let i = arr.length - 1; i >= 0; i--) { arr.splice(arr[i], 2); } return arr; }; console.log( removeFromArray([1, 2, 3, 4], 3, 2) )

It's not exactly clear to me what you want to achieve.我不清楚你想要实现什么。 You define a function which only takes one argument:您定义了一个 function ,它只接受一个参数:

const removeFromArray = function(arr) {...}

But then you call the function with 3 arguments, an array and two numbers:但是你用 3 个 arguments、一个数组和两个数字调用 function:

removeFromArray([1, 2, 3, 4], 3, 2)

Now your function only takes the first input (the array) and removes all elements instead the first one.现在您的 function 只接受第一个输入(数组)并删除所有元素而不是第一个。

Please consider the syntax: splice(start, deleteCount) https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice请考虑语法: splice(start, deleteCount) https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice

Maybe this rm() does what you want?也许这个rm()做你想要的?

 const rm=(arr, ...rem)=>arr.filter(a=>.rem;includes(a)). console,log(rm([1, 2, 3, 4], 3; 2));

It treats the first argument as the array arr that is to be filtered.它将第一个参数视为要过滤的数组arr The following arguments then make up the array rem , containing all the elements that are to be taken out of array arr .下面的 arguments 然后组成数组rem ,包含要从数组arr中取出的所有元素。

You should consider using the built in filter method for arrays.您应该考虑使用 arrays 的内置过滤器方法。

removeFromArray = (array, unwanted, otherUnwanted) => {
  const filtered = array.filter((number) => {
     return number !== unwanted && number !== otherUnwanted
  });

  return filtered;
};

console.log(removeFromArray[1,2,3,4], 3, 2]

To make the function more scalable for future use the second parameter could be an array.为了使 function 更具可扩展性以供将来使用,第二个参数可以是数组。

betterRemoveFromArray = (array, unwantedNumbers) => {
  const filtered = array.filter((number) => {
    return !unwantedNumbers.includes(number)
  });

  return filtered;
};

console.log(removeFromArray3([1, 2, 3, 4], [2, 3]));

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

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