var vacationSpots = ['Paris', 'New York', 'Barcelona'];
for(var i = vacationSpots.length - 1; i >= 0; i--) {
console.log('I would love to visit ' + vacationSpots[i]);
}
大家好,我的问题是 for 循环中“-1”中的逻辑是什么要反转。我明白了 for(var i = vacationSpots.length; i >= 0; i--) {
帮助您向后运行。但是 -1 在向后打印数组中的项目有什么用呢?
最佳答案
非常简单……数组长度是一个计数,但索引是从零开始的。
因此,如果 myArray
长度为 5,则最后一个索引为 4,并且 myArray[5]
不存在。
因此,当按索引迭代数组时,您不能超过最后一个索引,即 length-1
关于javascript - 需要 "-1"中的逻辑。在javascript中用数组进行for循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44246219/