我想在数组中找到两个相邻的元素 == 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/