javascript - 为什么 if 语句会阻塞在 while 循环中?

标签 javascript arrays loops if-statement

我有一个数字数组,其中有很多重复项。我需要摆脱它们,所以我输入了代码:

  let dup = arr.filter((elem, pos)=> arr.indexOf(elem) !== pos);
  // dup Array contains the duplicate numbers
  arr = arr.filter((elem, pos)=> arr.indexOf(elem) == pos);
  //arr contains the whole array with duplicates
  let i = 0;
  let j = 0;
  while(i<arr.length){
    while(j<dup.length){
      if(arr[i] == dup[j]){
        arr.splice(i, 1);
        //the splice method resets the decrease the index of the array so
        i--;
      };
      j++;
    };
    i++
  }

问题是 if 在第一个匹配之后没有运行。因此数组 splice 它找到的第一个重复项并停止。我该如何解决这个问题?

最佳答案

来自Get all unique values in a JavaScript array (remove duplicates)

const myArray = ['a', 1, 'a', 2, '1'];

const unique = [...new Set(myArray)]; 

// output ["a", 1, 2, "1"]

或者作为一个函数

const unique = [...new Set(myArray)]

关于javascript - 为什么 if 语句会阻塞在 while 循环中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56542643/

相关文章:

javascript - 如何使用定义文件创建 npm 包?

javascript - 如何在 jQuery 中按值对子项进行排序

JavaScript:在没有 64 位重定向的情况下读取注册表?

python - numpy 一维数组 : mask elements that repeat more than n times

c - 通过指针访问多维数组

javascript - 根据值合并两个不同长度的数组对象

javascript - jQuery 自动完成,输入触发另一个绑定(bind)

java - 从文件读取时获取与写入文件不同的字节数组

javascript - 数组推送在数组 forEach 中不起作用 - Javascript

python - 如何在此处使用 While 循环计时器?