在 JavaScript 中返回数组中第一个重复的数字

javascriptweb developmentobject oriented programming更新于 2025/10/12 21:32:17

我们需要编写一个函数,返回数组中至少出现两次的第一个元素的索引。如果没有元素出现超过一次,我们必须返回 -1。条件是我们必须在恒定空间中执行此操作(即不使用额外内存)。

让我们设计这个问题的解决方案。我们将使用 for 循环遍历数组并使用 Array.prototype.lastIndexOf() 方法检查重复项。

示例

const firstDuplicate = arr => {
   for(let i = 0; i < arr.length; i++){
      if(arr.lastIndexOf(arr[i]) !== i){
         return i;
      };
   };
   return -1;
}
console.log(firstDuplicate([3, 5, 6, 8, 5, 3])); // 0
console.log(firstDuplicate([0, 1, 2, 3, 4, 4, 5])); // 4
console.log(firstDuplicate([0, 1, 1, 2, 3, 4, 4, 5])); // 1
console.log(firstDuplicate([0, 1, 2, 3, 4, 9, 5])); // -1

输出

控制台中的输出将是 −

0
4
1
-1

相关文章


有用资源