javascript 循环遍历多维数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15525507/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Loop through multidimensional array
提问by Alosyius
How can i loop through the below multidimensional array?
如何遍历下面的多维数组?
I am creating the array like this:
我正在创建这样的数组:
var _cQueue = [[]];
And adding items like this:
并添加这样的项目:
var valueToPush = new Array();
valueToPush['[email protected]'] = '1234567';
_cQueue.push(valueToPush);
I want to loop through all different email adresses that are added, and then each random string associated with that email
我想遍历添加的所有不同的电子邮件地址,然后与该电子邮件关联的每个随机字符串
Any ideas?
有任何想法吗?
回答by Denys Séguret
First, you should not add elements to arrays by key, but to objects. Which means your global object should be build as :
首先,您不应该通过键向数组添加元素,而应该向对象添加元素。这意味着您的全局对象应该构建为:
var _cQueue = [];
var valueToPush = {}; // this isn't an array but a js object used as map
valueToPush['[email protected]'] = '1234567';
_cQueue.push(valueToPush);
Then, you iterate using two kinds of loops :
然后,您使用两种循环进行迭代:
for (var i=0; i<_cQueue.length; i++) { // iterate on the array
var obj = _cQueue[i];
for (var key in obj) { // iterate on object properties
var value = obj[key];
console.log(value);
}
}
See MDN's excellent Working with objects.
请参阅 MDN 出色的使用对象。
If you want to find the email associated to an id, you can do two things :
如果您想查找与 ID 关联的电子邮件,您可以做两件事:
1) loop until you find it :
1)循环直到你找到它:
function find(id) {
for (var i=0; i<_cQueue.length; i++) { // iterate on the array
var obj = _cQueue[i];
for (var key in obj) { // iterate on object properties
var value = obj[key];
if (value==id) return key;
}
}
}
2) put all the ids in a map so that it can be found faster :
2) 将所有的 id 放在一个地图中,以便可以更快地找到它:
var bigMap = {};
for (var i=0; i<_cQueue.length; i++) { // iterate on the array
var obj = _cQueue[i];
for (var key in obj) { // iterate on object properties
bigMap[obj[key]] = key; // maps the id to the email
}
}
function find(id) {
return bigMap[id];
}
回答by Adidi
use for-in to both levels:
在两个级别使用 for-in:
for(var val in _cQueue){
var obj = _cQueue[val];
for(var val1 in obj){
alert('key(email):' + val1 + '\nValue:' + obj[val1]);
}
}