开发者

Javascript / JQuery - How do I find the size of this array of objects?

I have this code to iterate through an array of objects:

for (vehicleIndex in scenes[sceneID].vehicles) {
  vehicleID开发者_Go百科 = scenes[sceneID].vehicles[vehicleIndex];
  ...
}

but I need to know how to determine the number of items being iterated through so that on the final item, I can execute a particular function. How do I do this?


Example in ES5:

Object.keys( scenes[sceneID].vehicles ).forEach(function( vehicle, index, arr ) {
    if( index === arr.length - 1 ) {
        // do something on last entry
    }
});

Even tho, "last" just means the last element which was looped over. Since there is specific order within a Javascript object (they are infact unordered). However, we could sort the object key names manually by just chaining a .sort() before the .forEach()


var arraySize = scenes[sceneID].vehicles.length;
var i;
var currentItem;
for (i = 0; i < arraySize; i++) {
  currentItem = scenes[sceneID].vehicles[i];
  if (i == arraySize - 1) {
    // do something special
  } else {
     // do something not so special ;-)
  }
}


scenes[sceneID].vehicles should have a length property.


for (vehicleIndex in scenes[sceneID].vehicles) {
  vehicleID = scenes[sceneID].vehicles[vehicleIndex];
  ...
}
doSomethingWithLastItem(vehicleId);

Because JS does not have block scope, by the time your loop finished vehicleId will be the last item's id.

In generic terms you can get the size of an array by accessing the .length property. You can also get the size of an object using Object.keys(obj).length.


Use this to find the length:

scenes[sceneID].vehicles.length

length is a built-in property in arrays. However, if you want to check for the last item, you have to check

scenes[sceneID].vehicles.length - 1

as arrays are zero-indexed.

Also, you should not use for...in to loop on arrays - if someone extends Array.prototype (or worse, Object.prototype), then you will not be happy. Use a normal for loop (which also allows you to use the final item easily):

var len = scenes[sceneID].vehicles.length;
for (var vehicleIndex = 0; vehicleIndex < len; vehicleIndex++) {
  vehicleID = scenes[sceneID].vehicles[vehicleIndex];
  //...
}
//Do something with the final item here
//Similar to this: itemFunc(vehicleID);

See this SO question for more details.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜