提示是找到数组中数字第四次出现的索引号。我正在尝试在for循环语句中实现中断,我不确定如何使其工作。这是我的代码:
let array = [0,4,4,3,2,1,4,5,6,4,6,9];
for (i = 0; i <= array.length; i++){
if (array[i] === 4){
console.log("The fourth occurrence of 4 is:", i)
break;
}
}
假设输出
The fourth occurrence of 4 is: 9
这将为你做的伎俩:
function getFourthOccurance(number){
let ocurrences = 0;
for (i = 0; i <= array.length; i++){
if (array[i] === number){
ocurrences++;
if(ocurrences === 4){
return i;
}
}
}
}
let array = [0,4,4,3,2,1,4,5,6,4,6,9];
console.log("The fourth occurrence of 4 is:", getOccurance(4))
你在找这个吗:
let array = [0,4,4,3,2,1,4,5,6,4,6,9];
let numberOfOccurencess = 0;
for (i = 0; i <= array.length; i++){
if (array[i] === 4){
numberOfOccurencess++;
}
if(numberOfOccurencess === 4) {
console.log('4th occurence is', i);
break;
}
}
请使用此代码。
let array = [0,4,4,3,2,1,4,5,6,4,6,9];
let count = 0;
const num = 4;
for (i = 0; i <= array.length; i++){
if (array[i] === num){
count++;
if(count === 4) {
console.log("The fourth occurrence of 4 is:", i)
break;
}
}
}