javascript - 在数组中查找两个重复值的最佳技术是什么?

标签 javascript arrays algorithm sorting

我想在数组中找到两个相邻的元素 == 1:2 或 1:3, 不计算第三个元素需要触发器 它可以正常工作,但它看起来很丑,我该如何优化它? 也许我可以跳过每个迭代中的下一个迭代,但是如何?

history["1:2", "1:11", "1:9", "1:6", "1:9", "1:2", "1:3", "1:10", "1:9", "1:3", "1:3"];

function getStats(history) {

    trigger = 0;
    dfault1 = 0;

    $.each(history, function(index, value) {
        if (((history[index] == '1:2') || (history[index] == '1:3'))  && ((history[index+1] == '1:2') || (history[index+1] == '1:3'))  ) {
            if (trigger == 0) {
                dfault1++;
                trigger = 1;
            } else {
                trigger = 0;
            }
        } else { 
           trigger = 0; 
        }
    });
    console.log(dfault1);
}

dfault1 = 2 因为

history[5] = '1:2' && history[6] = '1:3' dfault++ (1)

然后

history[9] = '1:3' && history[10] = '1:3' dfault++ (2)

附注对不起我的英语,如果你不明白 - 告诉我,我会纠正我的问题

最佳答案

这是清理它的一种方法。

function getStats(history) {
    matches = function(value) {
        return value == "1:2" || value == "1:3";
    };

    default1 = 0;
    prev = null;
    $.each(history, function(index, value) {
        if (matches(value) && matches(prev)) {
            default1++;
            prev = null;
            return true;
        }
        prev = value;
    });

    console.log(default1);
}

关于javascript - 在数组中查找两个重复值的最佳技术是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27626855/

相关文章:

ios - 在 AppDelegate 中使用来自 ViewController 的数组

arrays - 在 VBA 中替代使用 Array() 函数?

c# - 多个客户端之间的对象同步算法

javascript - 当鼠标悬停在 div 列上时如何在 map 上显示位置

javascript - 有条件地对范围进行排序

c++ - 使用循环调用具有不同名称的数组

algorithm - 根据平方根的小数部分找出一个数

algorithm - 给定一个未排序的整数数组 A,返回一个数组 B,其中 B[i] 是 A[j] 的数量,使得 A[i] > A[j] 而 i < j

javascript - svg 路径元素中的定向渐变

javascript - 如何处理 AMP 的 CORS