问题
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
}
I know that it would be more accurate to subtract 1 from the length, but why does the code above still work
回答1:
Almost. You have to:
- Decrease
i
instead of increasing it, and - Start from
array.length-1
, because array indexes start from 0, not 1.
So use instead:
for (let i = array.length-1; i >=0 ; i--) {
回答2:
It occurs cause arrays in Javascirpt are not limited to the size that they were declared. So, it implies that if you try to access an empty position you will receive undefined. For example, in this case, if you do array[5]
you will receive undefined
and not a ArrayIndexOutOfBoundsException
as it would happen in Java.
Also, you should take a look in your code. Since you're iterating the array backwards, you sohuld decrement i
with i--
instead of incrementing it.
回答3:
Because its like this:
const array = [1,2,3,4];
for(let i=10;i>=0;i--){
console.log(array[i]);
}
You can for cycle what ever you want. In javascript everything is an object, including array. Accessing something that does not exist in object with []
returns undefined.
回答4:
for(let i=array.length-1;i>=0;i--){
//do something
}
you need to set i
to the length of the array -1 (because array index starts at 0). Then each time you go through the loop you need to subtract one from i
(the i--
)
you code works but will run through the loop a huge amount of times until the number overflows into a negative. Try adding a console.log(i) to your loop to see what i mean. (it will likely freeze chrome if you do it in the inspector)
回答5:
The length of the Array is equal to the number of entries assuming they were all full. Sparse arrays do not have a length of the number of elements in them, but based on the maximum index in them
For example:
let a = [];
a[10] = 1;
console.log(a.length);
console.log(a);
The length is 11 (0 to 10) and you can see that there are values of undefined
for index 0 to 9.
Even setting the last value to undefined
does not affect the length since there is still a value of undefined
in that position.
let a = [];
a[9] = 1;
a[10] = 1;
console.log(a.length);
a[10] = undefined
console.log(a.length);
Using delete still does not affect the length.
let a = [];
a[9] = 1;
a[10] = 1;
console.log(a.length);
delete a[10];
console.log(a.length);
The only way to change the length is to create a new array as a subset of the original:
let a = [];
a[9] = 1;
a[10] = 1;
console.log(a.length);
console.log(a);
a = a.slice(0,9);
console.log(a.length);
console.log(a);
来源:https://stackoverflow.com/questions/55520074/looping-backwards-through-javascript-array-with-array-length-using-a-for-loop