简体   繁体   English

将数据保存为对象还是数组?

[英]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 如果我的值为4我想取回两个变量: a = 0.111b = 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: 您想要做的就是将其另存为json对象或数组,如下所示:

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: 在检索到的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(). 数组带有诸如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. 最后,归结为您要完成的工作的最佳工具。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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