使用for循环将重复项推送到Javascript中的单独数组中?

Shr*_*tel 5 javascript data-structures

出于某种原因,下面操作的 doubleArray 没有显示在控制台中。在这两种情况下,我在 for 循环之后声明的任何变量都不会显示在控制台上。考虑到在第一个算法中,只有一个 for 循环,每次都递增 x。而在第二种算法中,它是一个嵌套的 for 循环。有人可以帮我解决这两种算法中的错误吗?第一种算法:

var isDuplicate = function() {
  var helloWorld = [1,2,3,4,3];
  var doubleValue = [];
  var x = 0;
  for (i = 0; i < helloWorld.length; i++) {
    x = x + 1;
    if (helloWorld[i] === helloWorld[x] && i !== x) {
      doubleValue.push(helloWorld[i])
      console.log(helloWorld[i]);
    } else {
      continue;
    }
  }
  console.log(doubleValue);
};
Run Code Online (Sandbox Code Playgroud)

算法二:

var isDuplicate = function() {
  var helloWorld = [1,2,3,4,3];
  var doubleValue = [];
  for (i = 0; i < helloWorld.length; i++) {
    for (x = 1; x < helloWorld.length; i++) {
      if (helloWorld[i] === helloWorld[x] && i !== x) {
        doubleValue.push(helloWorld[x]);
      }
    }
  }
  console.log(doubleValue);
};
Run Code Online (Sandbox Code Playgroud)

Wai*_*mal 1

您的第一个算法不起作用,因为它只查找彼此相邻的重复项。您可以通过首先对数组进行排序,然后查找重复项来修复它。您还可以在循环中删除x并替换它。++i

var isDuplicate = function() {
  var helloWorld = [1,2,3,4,3,6];
  var doubleValue = [];
  helloWorld = helloWorld.sort((a, b) => { return a - b });
  for (i = 0; i < helloWorld.length; i++) {
    if (helloWorld[i] === helloWorld[++i]) {
      doubleValue.push(helloWorld[i])
      console.log(helloWorld[i]);
    } else {
      continue;
    }
  }
  console.log(doubleValue);
};

isDuplicate();
Run Code Online (Sandbox Code Playgroud)

对于第二个算法循环,您可能意味着在第二个循环中x++代替。i++这将解决问题。