Specifying initial value of `x` in `for(x in object)` loops
If I have the following code:
开发者_运维百科<html>
<body>
<script type="text/javascript">
var mycars = new Array();
mycars[0] = "Saab";
mycars[1] = "Volvo";
mycars[2] = "BMW";
var x = 1;
document.write("Value of x: " + x + "<br /><br />");
for (x in mycars)
{
document.write(x + ": " + mycars[x] + "<br />");
}
document.write("<br />Value of x: " + x + "<br />");
document.write("Number of cars: " + mycars.length);
</script>
</body>
</html>
I get the output:
Value of x: 1
0: Saab
1: Volvo
2: BMW
Value of x: 2
Number of cars: 3
Without changing the for-in loop to a for loop, is there any way to make it so the first element ("Saab") is not displayed? I would like the output to be:
Value of x: 1
1: Volvo
2: BMW
Value of x: 2
Number of cars: 3
Don't use for..in
loops to loop through arrays. Use for..in
only for looping through objects. Doing otherwise can have unintended consequences, that can seem baffling.
Use a standard for
loop:
for (var i = 0; i < mycars.length; i++)
{
document.write(i + ": " + mycars[i] + "<br />");
}
If you want to miss the first item out, set i
to 1
initially, rather than 0
. You should probably put a comment in, so you know what's happening if you ever come back to this bit of code.
You shouldn't use for..in loops to go through arrays anyway. From MDC:
"Also, because order of iteration is arbitrary, iterating over an array may not visit elements in numeric order."
So not only can you not skip the "first" element, you can't even rely on the first one being consistent!
To achieve exactly what you want, have such code:
var x = 1;
document.write("Value of x: " + x + "<br /><br />");
while (x < mycars.length) {
{
document.write(x + ": " + mycars[x] + "<br />");
x++;
}
x--;
document.write("<br />Value of x: " + x + "<br />");
document.write("Number of cars: " + mycars.length);
精彩评论