在Javascript中从2D数组的2层循环获取输出的最佳方法是什么?

时间:2013-07-23 12:30:53

标签: javascript arrays for-loop multidimensional-array

这是我的代码:

var myArray = {}; 
myArray["abc"] = new Array();
myArray["def"] = new Array();
myArray["abc"][0] = "John";
myArray["abc"][1] = "Mary"; 
myArray["abc"][2] = "Jack";  
var letter = "";
var id = "";

for (var i_letter in myArray)    {                
        for (var j_id = 0; j_id < myArray[i_letter].length; j_id++)  {                   
                if (myArray[i_letter][j_id]=== "Mary")  {
                      letter = i_letter;   // error ?
                      id = j_id;   // error?
                }
        }
}
document.write( letter + “ , ” + id);   // why error?  Suppose to be “abc , 1”  

从循环外部获取输出的最佳方法是什么,即i_letter和j_id? 顺便说一句,如果myArray包含大量数据,那么还是可以更有效地编写代码吗?

1 个答案:

答案 0 :(得分:1)

请看我的评论:

var myArray = new Array(); // error here
myArray["abc"] = new Array();
myArray["def"] = new Array();
myArray["abc"][0] = "John";
myArray["abc"][1] = "Mary"; 
myArray["abc"][2] = "Jack";  
var letter = '';
var id = '';

myLoop: // initial point of breaking outer for
for (i_letter in myArray) {               
        for (j_id=0; j_id < myArray[i_letter].length; j_id++)  {                   
                if (myArray[i_letter][j_id] === "Mary")  {
                      letter = i_letter;   
                      id = j_id;
                      break myLoop; // break from two for
                }
        }
}
document.write( letter + ' , ' + id); // error here because of using “ and ”

这种情况的最佳方法是设置循环的初始点myLoop,当找到Mary时,只需执行for即可停止执行break myLoop

jsfiddle上的演示。

希望这有帮助。