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

k5hmc34c  于 2022-12-17  发布在  Java
关注(0)|答案(3)|浏览(116)

我试过了

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

如果我想从数组中删除数字,我应该怎么做?

ecfsfe2w

ecfsfe2w1#

您可以将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

或者作为variadic argument

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
unftdfkk

unftdfkk2#

我想你可以使用一个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)
0dxa2lsx

0dxa2lsx3#

以下是我的版本

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

相关问题