Javascript:如何找到第一个重复值并返回其索引? [英] Javascript: How to find first duplicate value and return its index?

查看:100
本文介绍了Javascript:如何找到第一个重复值并返回其索引?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须在数组中找到第一个重复值,然后在变量firstIndex中返回其索引。这必须通过for循环来完成,它应该在找到第一个重复之后停止。我知道这可能很简单,但我卡住了。到目前为止,我有这个,但它似乎没有工作:

I have to find first duplicate value in array and then return its index in variable firstIndex. This has to be done with for loop which should stop after having found first duplicate. I know this is probably pretty simple but I got stuck. So far I have this but it doesn't seem to be working:

var numbers4 = [5, 2, 3, 4, 2, 6, 7, 1, 2, 3];
var firstIndex = "";
for (var a = 0; a < numbers4.length; a++) {
    for (var b = a+1; b < numbers4.length; b++) {
        if (numbers4[a] === numbers4[b])
            firstIndex = numbers4.indexOf(numbers4[a]);
            break;
    }
}
console.log(firstIndex);

控制台打印出1,这很好,因为2是第一次复制,但当我更改数组中的数字时,循环不起作用。你能告诉我这里可以改变什么吗?

Console prints out 1 which is fine because 2 is first duplicate, but when I change numbers in array, the loop doesn't work. Can you advise what can be changed here?

提前致谢!

推荐答案

使用以下内容更改您的代码

Change your code with the following

    var numbers4 = [5, 2, 3, 4, 2, 6, 7, 1, 2, 3];
    var firstIndex = "";
   var isMatch=false;
    for (var a = 0; a < numbers4.length; a++) {
        for (var b = a+1; b < numbers4.length; b++) {
            if (numbers4[a] === numbers4[b]){
                firstIndex = numbers4.indexOf(numbers4[a]);
                isMatch=true;
                break;
          }
        }
           if (isMatch) {break;}
    }
    console.log(firstIndex);

这篇关于Javascript:如何找到第一个重复值并返回其索引?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆