Is javascript in-function only returning an index?

This is the method I tried to run:

function SayHello() {
    cars = new Array();
    cars[0] = "Toyota";
    cars[1] = "Mitsubishi";
    cars[2] = "Honda";

    for (car in cars) {
        alert(car);
    }
}

This returns:

0
1
2

When I changed the code to this:

function SayHello() {
    cars = new Array();
    cars[0] = "Toyota";
    cars[1] = "Mitsubishi";
    cars[2] = "Honda";

    for (car in cars) {
        alert(cars[car]);
    }
}

He correctly returned the names.

My question is, does the for-in loop just return the index in an ordered manner? Thank.

+5
source share
4 answers

Yes, it will be an index within collections.

Look here :

var mycars = ["Saab", "Volvo", "BMW"];

for (var car in mycars)
{
  document.write(mycars[car] + "<br />");
}

As you can see, using a variable as an index in a collection.

You can use the syntax for each ... in(introduced in Javascript 1.6) that will iterate over the values. See here .

for each...in - for...in, , . ( JavaScript 1.6.)

, Javascript 1.6+ Firefox .

+5

, - . , , . , :

x = ['a', 'b', 'c'];

x.foo = 'bar';

for (i in x) alert(i);  // 0, 1, 2, foo

:

x = { a : 'apple', b : 'banana', c : 'carrot' };

for (i in x) {
    // and it best to check that the property actually exists
    // on this object, not just on one of its prototypal ancestors:
    if (x.hasOwnProperty(i)) {
        alert(i);  // 'a', 'b', 'c'
    }
}

, YUI

+8

. , , . "0", "1" ..

, for in , javascript .

+1

It returns the "key" of each item. The same result will be achieved using such an "array":

cars = {0: "Toyota", 1: "Mitsubishi", 2: "Honda"};
+1
source

All Articles