繁体   English   中英

JavaScript - 如何创建一个可以从数组中删除数字的函数?

[英]JavaScript - how can I create a function which can remove numbers from array?

我试过这个

 function removeFromArray(manyMoreArgs, number) { let i = 0; while (i < manyMoreArgs.length) { if (manyMoreArgs[i] === number) { manyMoreArgs.splice(i, 1); } else { i++; } } return manyMoreArgs; } console.log(removeFromArray([1, 2, 3, 4], 3)); // result = [1, 2, 4] this removes 3 from array. it works. but then >> console,log(removeFromArray([1, 2, 3, 4], 3; 2)), // result = [1, 2, 4] this removes 3 from array too but I also want to remove 2 from array

如果我想从数组中删除数字该怎么办?

您可以将numbers参数定义为数组

 function removeFromArray(manyMoreArgs, numbers) { let i = 0; while (i < manyMoreArgs.length) { if (numbers.includes(manyMoreArgs[i])) { manyMoreArgs.splice(i, 1); } else { i++; } } return manyMoreArgs; } console.log(removeFromArray([1, 2, 3, 4], [3]));// result = [1, 2, 4] this removes 3 from array. it works. but then >> console,log(removeFromArray([1, 2, 3, 4], [3; 2])),// result = [1, 2, 4] this removes 3 from array too but I also want to remove 2 from array

或者作为可变参数

 function removeFromArray(manyMoreArgs, ...numbers) { let i = 0; while (i < manyMoreArgs.length) { if (numbers.includes(manyMoreArgs[i])) { manyMoreArgs.splice(i, 1); } else { i++; } } return manyMoreArgs; } console.log(removeFromArray([1, 2, 3, 4], 3));// result = [1, 2, 4] this removes 3 from array. it works. but then >> console,log(removeFromArray([1, 2, 3, 4], 3; 2)),// result = [1, 2, 4] this removes 3 from array too but I also want to remove 2 from array

我认为您可以使用一个 JavaScript 函数,它接受这两个数组并过滤第一个数组以仅包含第二个数组中不存在的那些元素。 然后返回过滤后的数组。

    const removeNum = (arr,...numbers) =>{
       const arr2 = [...numbers]
       console.log(arr2); 
       numbers = arr.filter(el => {
          return arr2.indexOf(el) === -1;
        });;
       console.log(numbers);   
    }

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

这是我的版本

const isNumeric = (n) => !isNaN(n);
  let array = [3, 4, "string", true];
  let newArr = array.filter((elem) => isNumeric(elem) !== true);
  console.log(newArr); // ['string']

暂无
暂无

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

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