使用for循环向后遍历具有array.length的javascript数组 [英] Looping backwards through javascript array with array.length using a for-loop
本文介绍了使用for循环向后遍历具有array.length的javascript数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果我有一个要循环遍历的数组= [8,7,6,5,4],
为什么下面的for循环仍然有效,但是数组的长度为5并且有数组索引5处没有元素?
If I have an array = [8,7,6,5,4] that I want to loop through, why does the following for loop still work yet the length of the array is 5 and there is no element at index 5 of the array?
for(let i=array.length;i>=0;i++){
//do something
}
我知道这样会更准确从长度中减去1,但是上面的代码为什么仍然有效
I know that it would be more accurate to subtract 1 from the length, but why does the code above still work
推荐答案
几乎。您必须:
- 减少
i
而不是增加它,并且 - 从
array.length-1
开始,因为数组索引从0开始,而不是1。
- Decrease
i
instead of increasing it, and - Start from
array.length-1
, because array indexes start from 0, not 1.
因此改用:
for (let i = array.length-1; i >=0 ; i--) {
这篇关于使用for循环向后遍历具有array.length的javascript数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文