javascript - 了解查找重复数字并返回第二次出现的最低索引

标签 javascript arrays

关于在数组中查找第二次出现的第一个重复数字具有最小索引的问题。

如果我到目前为止理解,变量firstDuplicate是一个函数对象,它使用箭头表示法缩写“varfirstDuplicate=function(a){}”等。这就是我的问题开始的地方。

1) 使用函数传递的数组创建一个新的 set 对象自动填充? set 方法如何知道获取传递给函数的数组并对其进行设置?

2) 现在我明白在 for 循环中,数组中的每个项目都被遍历,当前索引是 e,但这里是我开始在概念上丢失正在发生的事情的地方。位于以下位置:

if (r.has(e))

比较到底发生在哪里,即检查此数组中的重复数字是什么,以及确定第二次出现的重复数字的最低索引是什么的比较?

const test1 =  [0, 3, 4, 10, 2, 4, 2, 3]
  firstDuplicate = a => {
    r = new Set()
             for (e of a)
        if (r.has(e))
          return e
      else
        r.add(e)
return -1
}

console.log(firstDuplicate(test1));

最佳答案

Creating a new set object automatically populates using the array the function was passed? How does the set method know to take the array passed to the function and make a set of it?

这里没有任何事情会自动发生。当您说 r.add(e)

时,Set 会在 else 条件中填充

Now I understand in the for loop that each item in the array is being traversed and the current index is e...

e 是当前元素,而不是当前索引。您正在使用 for..of声明而不是 for..in陈述。使用简单片段来区分两者的区别

const a = [10, 5, 12];

console.log("for..in statement");
for (const i in a) {
  // Here i is the index
  console.log(i)
};

console.log("for..of statement");
for (const i of a) {
  // Here i is the element
  console.log(i)
};

...where is the comparison happening exactly, that is the checking to see what the duplicative numbers are in this array, and the comparison that determines what the lowest index of the second occurrences of the duplicate are?

比较发生在r.has(e)处。因此,代码检查是否已遇到 e(因此也添加到 Set 中)并返回 e。这是有效的,因为如果 e 已经遇到过一次,那么如果在任何其他重复项之前再次遇到它,它会自动意味着 e 位于最小索引。

这是您的代码的注释版本,以使其更加清晰

const test1 = [2, 3, 6, 10, 2, 3, 7, 9, 1]

firstDuplicate = a => {
  // Create an empty Set
  r = new Set()

  // Iterate over every element of a
  for (e of a) {
    // Check if e was already encountered
    if (r.has(e)) {
      // If e was already encountered, this is the first time a duplicate
      // has been found. This is definitely a duplicate at the minimal index,
      // as a for loop iterates elements in order of their indices
      return e
    } else { // e is encountered the firt time
      // Populate the Set with e, to say that it has been encountered atleast
      // once
      r.add(e)
    }
  }
  // The if condition above never passed. That means array a has all
  // unique elements. Return -1, assuming the array a will never contain
  // -1 as one of it's elements.
  return -1
}

console.log(firstDuplicate(test1));

关于javascript - 了解查找重复数字并返回第二次出现的最低索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45131104/

相关文章:

javascript - 如何使用js删除当前类?

javascript - 以下JS结构的目的是什么?

javascript - 使用javascript中的搜索字符串过滤嵌套的对象数组

C# 隐式数组声明

php - Smarty in_array 值

javascript - 如果等于其他输入值则更改输入值

javascript - javascript如何调用iframe加载文件的函数

javascript - 多次启动轨道 slider 的问题

c# - 什么时候在 C# 中使用 ArrayList 而不是 array[]?

C - 当未转换为其类型的指针时,数组名称是什么?