Especificando el valor inicial de `x` en` for (x en objeto) `bucles

Si tengo el siguiente código:

<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>

Obtengo la salida:

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

preguntado el 09 de enero de 11 a las 09:01

you can add a if condition .. -

mira esto propuesta. -

3 Respuestas

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!

Respondido el 09 de enero de 11 a las 12:01

No 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.

Utilice un estándar for bucle:

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 a 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.

Respondido el 09 de enero de 11 a las 12:01

Oh well, I guess I'll just stick to the C++ way of doing it. :) - Mateen Ulhaq

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);

Respondido el 09 de enero de 11 a las 12:01

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.