Loop Through Object in Javascript

Possible Duplicate:
Loop through Json object

{"data":[{"name":"Jen","id":"1"},{"name":"Steve","id":"8"}]}

A server I'm interacting with responds with the above.

I'm trying to loop through it for the For..in statement.

This is what I'm trying to do:

for (var item in response.data)
{
console.log(item.name);
}

This doesn't work. What went wrong?

Thank you

I GOT IT to work with the following after reading the comment:

for (var item in response.data){ console.log(response.data[item].name); } })

I was able to get a list of names...

Can someone dissect the response as to why it worked?


Check out: Why is using "for...in" with array iteration a bad idea?

For...in iterates through names of the properties of an object. Array items are also considered "properties", so for..in iterates through indexes (which are 0, 1 in your case). As expected when you use response.data[0] you get first element of your array.


data is actually an array (denoted by [] ), rather than an object so you want a regular for loop rather than a for in .

for (var i = 0; i<response.data.length; i++) {
  // use i as an array index
  console.log(response.data[i].name);
}

In JavaScript, the for in construct is used for iterating over object properties, but to iterate an array an incremental for loop is typically used.


for..in iterates over the enumerable properties of an object in no particular order (you may get a different order in different browsers). An array is just a plain object with a special length method and handy methods inherited from Array.prototype (some of which depend on the special length property). There is no restriction on what can be used for a property name, they are not restricted to non-negative integers (noting that where a properly name is not a valid identifier, square bracket notation must be used to access its value).

The indexes of an array are just string property names (ie they are just plain object property names) that are non-negative integers, so a for..in loop will iterate over the numeric indexes (again, not necessarily in ascending or descending order) as well as all other enumerable properties, including those on the [[Prototype]] chain . Therefore it is always recommended to include a hasOwnProperty test with for..in unless you want to include inherited enumerable properties.

Because of the above, it is generally much better to iterate over array properties using a counter from 0 to array.length - 1 (since the length is always one bigger than the last index).

To test the "no particular order" statement, try the following in IE and other browser and note the different order:

var a = [];
a[2] = 2;
a[0] = 0;
a[3] = 3;
var b = [];
for (var i in a) b.push(a[i]);
alert(b);
链接地址: http://www.djcxy.com/p/28828.html

上一篇: 在Ajax响应中循环一个json对象

下一篇: 在Javascript中循环对象