3

I was dealing with a problem and got to the point where I thought I could use the Ids to my entity instances as array indices for easy lookup.

var myArray = [];
myArray[obj.Id] = true;

Assume obj.Id is 1000 here, so will be myArray.length. Am I allocating 1000 bytes for a single boolean value here or is it just returning the maximum index as length?

Vahid
  • 1,829
  • 1
  • 20
  • 35

1 Answers1

2

It won't be allocating so many bytes.

But what you are really looking for is an key-value object like

var myObj = {};
myObj[obj.Id] = true;
//then to access
console.log(myObj[obj.Id])
Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
  • Thanks. Yes I did use the object approach eventually. I was just interested to know if array space allocation is based on index. – Vahid Mar 29 '16 at 05:14
  • And could you please explain why is using objects rather than array is a better approach then? – Vahid Mar 29 '16 at 05:18