我试图从数组中排除元素,但我做错了什么

I'm trying to exclude elements from an Array, but I'm doing somthing wrong

我正在尝试创建这个脚本:https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/seek-and-destroy

在评论“验证并删除”之后我遇到了问题。 我尝试用 'destroyers' 中的元素检查数组 'theCheck' 中的所有元素,如果元素不匹配,那么脚本会将那个值推送到输出数组。

但它无论如何都会推动每个元素。

预期输出值:[1,1]

当前输出值value:[1,2,3,1,2,3]

function destroyer(arr) {

  let theCheck = [];
  let destroyers = [];
  let output = [];

  for (let i = 1; i < arguments.length; i++) {
    destroyers.push(arguments[i]);
  }

  for (let i = 0; i < arguments[0].length; i++) {
    theCheck.push(arguments[0][i])
  }

  //Verify and delete
  var j = 0
  for (let i = 0; i < theCheck.length; i++) {
    for (j = 0; j < destroyers.length; j++) {
      if (theCheck[i] !== destroyers[j]) {
        output.push(theCheck[i])
        break;
      }
    }
  }

  console.log(theCheck)
  console.log(destroyers)
  console.log(output)
  return arr;
}

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

使用当前代码,您将遍历驱逐舰,并且只要您发现与您正在检查的项目不匹配的驱逐舰,您就会将其添加到输出中。但是因为你在 destroyers 数组中有两个项目,所以可以保证这两个项目之一不会匹配你正在检查的特定项目。

下面是一个版本,我们在其中计算是否发现任何驱逐舰与我们正在检查的项目相匹配,并且仅当不匹配时我们才将其添加到输出中:

function destroyer(arr) {

  let theCheck = [];
  let destroyers = [];
  let output = [];

  for (let i = 1; i < arguments.length; i++) {
    destroyers.push(arguments[i]);
  }

  for (let i = 0; i < arguments[0].length; i++) {
    theCheck.push(arguments[0][i])
  }

  //Verify and delete
  var j = 0
  for (let i = 0; i < theCheck.length; i++) {
    let found = false;
    for (j = 0; j < destroyers.length; j++) {
      if (theCheck[i] === destroyers[j]) {
        found = true;
      }
    }
    if(!found) output.push(theCheck[i]);
  }

  console.log(theCheck)
  console.log(destroyers)
  console.log(output)
  return arr;
}

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

您可以使用 includes 函数稍微整理一下:

function destroyer(arr) {

  let theCheck = [];
  let destroyers = [];
  let output = [];

  for (let i = 1; i < arguments.length; i++) {
    destroyers.push(arguments[i]);
  }

  for (let i = 0; i < arguments[0].length; i++) {
    theCheck.push(arguments[0][i])
  }

  //Verify and delete
  var j = 0
  for (let i = 0; i < theCheck.length; i++) {
    if(!destroyers.includes(theCheck[i]))
      output.push(theCheck[i]);
  }

  console.log(theCheck)
  console.log(destroyers)
  console.log(output)
  return arr;
}

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

function destroyer(input, ...arr) {
   return input.filter(element => !arr.includes(element)); 
}

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