如何使用Javascript数组方法比较数组中的不同索引



我试图解决下面的问题,但我被困在知道如何比较一个索引与另一个索引,而不是结果,例如:

const arr = ["Juan", "Maria", "Maria", "Juan"]

在这种情况下,比较索引1和2将是简单的,但我如何选择索引0,然后将其与其他每个索引0进行比较,直到到达要匹配的索引3呢?

输入:美国、澳大利亚、澳大利亚、印度、法国、美国

打印出国家名称和"Bingo"如果元素(国家名称)重复并且一个接一个地位于

打印出国家名称和字样"万岁";如果元素(国家名称)重复且定位结果不是

注意:可以使用任意Array方法

预期结果:"Bingo Australia"万岁USA">

这是我试过的。

请注意,如果我以这种方式运行,它会工作,但只是因为我访问的是国家[index + 5]。

如何使索引在迭代结束时动态增加?

const countries = ['USA', 'Australia', 'Australia', 'France', 'India', 'USA'];
countries.forEach((value, index) => {
if (countries[index] === countries[index + 1]) {
console.log(`Bingo ${value}`);
} else if (countries[index] === countries[index + 5]) {
console.log(`Hooray ${value}`);
}
});

你可以尝试这样做,这不是最有效的,但它会解决你的问题:

=const国家(美国,澳大利亚,澳大利亚,法国,印度,'美国'],

countries.forEach((value, index, arr) => {
arr.forEach((val, idx) => {
if (val === value && index < idx) {
if (idx === index + 1) console.log(`Bingo ${value}`);
else console.log(`Hooray ${value}`);
}
});
});

使用大量'if'的解决方案(只需减少迭代(循环计数))为了for循环而写,实际上,它与嵌套循环相同。

const c_arr = [1, 4, 5, 5, 6, 7, 4, 1];
let j = 0;
let full_count = 0; //count loops
for (let i = 0; i < c_arr.length; ++i) {
if (j === 0 & c_arr[i] === c_arr[i + 1]) { // condition j ==0 so it will go inside only in first loop
console.log('Bingo', c_arr[i])
}
// console.log("Test", c_arr[j]);
if (i + 2 < c_arr.length & c_arr[j] === c_arr[i + 2]) { // i+2 cond, to avoid to access elem. outside array
console.log('Hooray', c_arr[i + 2]);
c_arr[j] = null;
}
// All to reduce loop count
if (j > 0 & c_arr[j] === null) { // allneigbourgh elements are checked
i = j;
++j;
}
if (j > 0 & i === c_arr.length - 3) { // avoid empty loop, condition for Hooray is i+2
i = j;
++j;
}
if (i === c_arr.length - 1) { // on first loop increase j
i = j;
++j;
}
// to stop loop when J reaches arr :-2 element
if (j === c_arr.length - 2) {
i = c_arr.length;
}
++full_count;
}
console.log(full_count, " :loops count");

最新更新