简体   繁体   中英

saving data as object or array?

I have some data like

4 0.128 0.039
5 0.111 0.037
6 0.095 0.036

I need to get the second and third value by a known first value. If I have a value of 4 I want to get back two variables: a = 0.111 and b = 0.037

What would be the best variable type for storing the data shown above to get simple access to the data? An object or an multidimensional array?

For ease of access, I'd go with an object containing arrays:

{
    '4': [ 0.128, 0.039 ],
    '5': [ 0.111, 0.037 ],
    ... 
}

A second reason for the use of objects over arrays is ease of iteration. Imagine this:

var myData = [];
myData[4]  = [ 0.128, 0.039 ];
myData[10] = [ 42, 23 ];

for (var i = 0; i < myData.length; i++)
{
    console.log(myData[i]);
}

Would give you

null
null
null
null
[ 0.128, 0.039 ]
null
null
null
null
null
[ 42, 23 ]

... which is probably not what you want ;)

What you would want to do is save it as a json object or just as an array as shown below:

Creating:

var obj = { "4":[0.128, 0.039], "5":[0.111, 0.037],"6":[0.095, 0.036] }

Retrieving:

obj.4 -> [0.128, 0.039] OR obj['4'] OR obj[0]
obj.5[0] -> 0.111 OR obj['5'][0] OR obj[1][0]
obj.5[1] -> 0.037 OR obj['5'][1] OR obj[1][1]

Cycling through retrieved obj:

for (var key in obj) {
    alert(obj[key]); 
}

I personally use arrays if the order of the elements is of importance, otherwise I use objects (objects are not good for preserving order).

  • Arrays come with methods like push(),pop(),sort(),splice().
  • Objects are good if you have a unique key.

In the end it comes down to what is the best tool for what is that you want to accomplish.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM