用Javascript创建数组 [英] Creating arrays in Javascript

查看:49
本文介绍了用Javascript创建数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对javascript并不陌生,在用JavaScript制作2d(或者也许我可能需要3d)数组时,我遇到了很多麻烦.

I am little new to javascript and I am having alittle trouble wrapping my head around making a 2d (or maybe i might need a 3d) array in javascript.

我目前需要收集2条信息:一个ID和一个值,因此我创建了以下内容:

I currently have 2 pieces of information i need to collect: an ID and a value so I created the following:

var myArray = [];

var id = 12;
var value = 44;

myArray[id]=value;

但是我意识到这不容易像for循环那样遍历整个数组,所以我想到了这一点:

But I realized that this is not easy to loop through the array like a for loop so i was thinking of this:

myArray[myArray.length] = id;
myArray[myArray.length-1][id]=value;

我想这样做,以便在for循环中我可以轻松获得id和值,但是以上内容仅在我循环遍历时返回该值.关于如何使它正常工作的任何建议,或者有更好的方法吗?

I wanted to do this so that in a for loop i could get the ids and the values easily but the above only returns the value when i loop through it. Any suggestions on how to get this working or is there a better way to do this?

谢谢

推荐答案

为什么不使用对象哈希是吗?这种方法允许您以key:value格式存储多个值:

Why not use an array of object hashes? This approach allows you to store multiple values in a key:value format:

var myArray = [];
var myElement = {
  id: 12,
  value: 44
}

myArray[0] = myElement;

然后您可以像这样循环遍历myArray中的所有元素:

You could then loop through all of the elements in myArray like so:

var i = 0,
    el;

while (el = myArray[i++]) {
  alert(el.id + '=' + el.value);
}

这篇关于用Javascript创建数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆