我有一个包含对象的数组。我需要在循环中找到第一个重复值。我想我需要使用 break,但它不起作用。
这是我的代码:
var arrWithNumbers = [2,4,5,2,3,5,1,2,4];
var firstIndex = 0;
for(var i=0; i<10; i++) {
if(arrWithNumbers.length == firstIndex[i]) {
firstIndex = arrWithNumbers;
break;
}
}
console.log(firstIndex);
最佳答案
您可以循环直到获得与实际索引相同编号的索引。
本提案使用Array#indexOf
fromIndex
大于实际索引。
var array = [2, 4, 5, 2, 3, 5, 1, 2, 4],
index = 0,
second;
while (index < array.length) {
second = array.indexOf(array[index], index + 1);
if (second !== -1) {
break;
}
index++;
}
console.log(index);
console.log(second);
哈希表方法
var array = [2, 4, 5, 2, 3, 5, 1, 2, 4],
index = 0,
hash = Object.create(null);
while (index < array.length) {
if (array[index] in hash) {
break;
}
hash[array[index]] = index;
index++;
}
console.log(hash[array[index]], index);
关于javascript - 如何找到数组中的第一个频率值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43868960/