了解查找重复数字并返回第二次出现的最低指数

时间:2017-07-16 16:52:28

标签: javascript arrays

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

如果我理解到目前为止,变量firstDuplicate是一个函数对象,它使用箭头符号来缩写'var firstDuplicate = 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));

1 个答案:

答案 0 :(得分:0)

  

使用传递函数的数组自动填充新的set对象? set方法如何知道将数组传递给函数并生成一组呢?

这里没有任何事情自动发生。当您说Set

时,else条件会填充r.add(e)
  

现在我在for循环中理解正在遍历数组中的每个项目并且当前索引是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)
};

  

...确切地说比较发生在哪里,就是检查这个数组中重复数字是什么,以及确定副本第二次出现的最低索引是什么的比较?

比较发生在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));