let vacationSpots = ['USA', 'UK', 'Colombia'];
for (let vacationSpotIndex = vacationSpots.length - 1; vacationSpotIndex >= 0; vacationSpotIndex-- ) {
console.log('I would love to visit ' + vacationSpots[vacationSpotIndex]);
}
我假设长度为3,我们减去1,所以等于2; 所以索引开始是2,我们在每个循环中都减去1 条件中的问题 vacationSpotIndex> = 0 从逻辑上讲,我认为是VacationSpotIndex <= 0
答案 0 :(得分:2)
我可能是错的,但似乎您的问题是,为什么是vacationSpotIndex >= 0
而不是vacationSpotIndex <= 0
?答案是,在每次循环之前都要检查for循环的条件。您的意思是,“只要 vacationSpotIndex >= 0
就运行这个循环”。一旦该条件不再成立,循环将停止运行。因此它将递减2、1、0,-1,然后由于-1不大于或等于零,因此循环将停止。
答案 1 :(得分:0)
数组的索引从javaScript中的0开始
一切正常工作。这里没有错。
let vacationSpots = ['USA', 'UK', 'Colombia'];
vacationSpots.length=3
index->0='USA'
index->1='UK'
index-2='Colombia'
用于(让VacationSpotIndex = vacationSpots.length-1; vacationSpotIndex> = 0; vacationSpotIndex--){
vacationSpotIndex >= 0;
此条件表示要迭代循环,直到VacationSpotIndex大于或等于零,并在每次迭代之前检查该循环。
循环将从index = 2开始,直到index = 0
vacationSpotIndex=2
vacationSpotIndex=1
vacationSpotIndex=0
答案 2 :(得分:-3)
虽然您使用> = 0,所以当它为0时它将继续循环,因此导致超出范围(-1)使其变为> 0
let vacationSpots = ['USA', 'UK', 'Colombia'];
for (let vacationSpotIndex = vacationSpots.length - 1; vacationSpotIndex > 0; vacationSpotIndex-- ) {
console.log('I would love to visit ' + vacationSpots[vacationSpotIndex]);
}