How best to do a JavaScript array with non-consecutive indexes?

前端 未结 7 901
野性不改
野性不改 2020-12-06 00:09

I\'m writing a Google Chrome extension, in JavaScript, and I want to use an array to store a bunch of objects, but I want the indexes to be specific non-consecutive

7条回答
  •  我在风中等你
    2020-12-06 00:59

    You can simply use an object instead here, having keys as integers, like this:

    var myObjects = {};
    myObjects[471] = {foo: "bar"};
    myObjects[3119] = {hello: "goodbye"};
    

    This allows you to store anything on the object, functions, etc. To enumerate (since it's an object now) over it you'll want a different syntax though, a for...in loop, like this:

    for(var key in myObjects) {
      if(myObjects.hasOwnProperty(key)) {
        console.log("key: " + key, myObjects[key]);
      }
    }
    

    For your other specific questions:

    My question is: does this matter? Is this wasting any memory?

    Yes, it wastes a bit of memory for the allocation (more-so for iterating over it) - not much though, does it matter...that depends on how spaced out the keys are.

    And even if it's not wasting memory, surely whenever I loop over the array, it wastes CPU if I have to manually skip over every missing value?

    Yup, extra cycles are used here.

    I tried using an object instead of an array, but it seems you can't use numbers as object keys. I'm hoping there's a better way to achieve this?

    Sure you can!, see above.

提交回复
热议问题