Javascript array object arrays

THis is going to sound like a stupid question but here it goes. I have a js array formatted like so

 var locationID = [
              { ID: "ID1", location: "location1" },
              { ID: "ID2", location: "location2" },
              { ID: "ID3", location: "location3" },
   ];

I am trying to loop through the array

for(i = 0; i < locationID.length;i++){
   var object = locationID[i];
}

I want to get both elements from the inner array so the ID and location. would I do this by object[0] or object["ID"] for example.

Also is there a more efficient way to do what I need to do like a for each loop or something along those lines.


Use object.ID or object['ID'] .

Objects {} in JavaScript are associative, or named arrays. (Also known as a map in many languages. They are indexed by strings (in this case).

Arrays [] , are indexed by integral numbers, starting from 0 and counting up to n-1 , where n is the length of the array.

If you want to programmatically go through all the (key, value) pairs in each object, you can use this method.

Quotations (String Literals)

To reiterate my comment below about single and double quotes:

If you're talking about inside the [] , no [,they're not important]. JavaScript treats single quotes and double quotes pretty much the same. Both of them denote string literals. Interestingly, you can use single quotes inside double quotes or vice-versa: "I wanted to say 'Hello world!'" would be a (single) valid string, but so would 'But I accidentally said "Goodbye" .


This is an optimized loop based from the book of Nicholas Zackas (YAHOO performance chief). I am performing a cached array length to prevent re-evaluation of array length on every iteration of the loop. Please check jsperf.com. Also, native loop is always faster than method based loops jQuery.each and Array.prototype.forEach. This is also supported on browsers below ie8

    var currentItem,
        locationInfo = [
          { ID: "ID1", location: "location1" },
          { ID: "ID2", location: "location2" },
          { ID: "ID3", location: "location3" },
        ];

    for (var i = 0, len = locationInfo.length; i < len; i++) {
        currentItem = locationInfo[i];

        console.log(currentItem.ID);//I prefer this because it shrinks down the size of the js file
        console.log(currentItem["ID"]);
    }

what you have already will return each of the objects in the JSON as you run the loop. What you need is something like

for(i = 0; i < locationID.length;i++){
   var object = {locationID[i].ID, locationID[i].location};
}

Remember properties of objects are accessed by their keys since they are key-value pairs.

链接地址: http://www.djcxy.com/p/70010.html

上一篇: 循环条件缓存数组长度是否会影响性能?

下一篇: Javascript数组对象数组