2010-08-27 153 views
1

我想遍历嵌套数组var,并选择那些满足单个条件的数组元素。我试图仅在“el”中找到“selectedIndex”时才选择内部数组的所有第一个元素(“choice1,choice2 ...”)。例如:如果从下拉菜单中选择“opt2”,它不应该选择元素“choice2”和“choice4”,因为不存在该数组的“2”,但它应该得到所有其他的(choice1,choice3, choice5)。演示请点击here。 非常感谢提前。选择嵌套数组中的元素

var all_data = new Array(
    new Array("selection1", new Array(
     new Array("choice1", new Array('a', [1, 2, 3, 4]), new Array('b', [3, 4])), 
     new Array("choice2", new Array('a', [3, 4]), new Array('b', [1, 4]), new Array('c', [1, 3, 4])) 
    )), 
    new Array("selection2", new Array(
     new Array("choice3", new Array('a', [2, 4]), new Array('b', [1, 3, 4]), new Array('c', [3, 4])), 
     new Array("choice4", new Array('b', [1, 4]), new Array('c', [1, 3])), 
     new Array("choice5", new Array('b', [1, 2, 4]), new Array('c', [1, 2, 3, 4])) 
    )) 
); 

function arraySearch(arr, i) { 
    var result = []; 
    for (var i = 0; i < arr.length; i++) { 
    for (var j = 0; j < arr[i].length; j++) { 
     for (var k = 0; k < arr[i][j].length; k++) { 
      var el = arr[i][j][k]; 
      if (el instanceof Array) { 
       //alert(el); 
       //here i want to check if 'i' exists in each 'el' 
       //and if found, concat the element "choice1, choice2..." 
      } 
     } 
    } 
    } 
    return result; 
} 
function getChoices(){ 
    selected_method = document.form.method.selectedIndex; 
    var n = selected_method+1; 
    var elements = arraySearch(all_data, n); 
    //alert(elements); 
}  
    <select name="method" onchange="getChoices();"> 
     <option>opt1</option> 
     <option>opt2</option> 
     <option>opt3</option> 
     <option>opt4</option> 
    </select> 
+0

您可以通过用* [*] *替换* new Array(...)*来节省一些输入。所以,它会更像* var all_data = [[“selection1”,[[“choice1”,['a',[1,2,3,4]]]]]] * – 2010-08-27 20:59:21

回答

2

使用递归循环嵌套数组或在搜索之前将数组拉平。

function recursiveArraySearch(arr, filter) { 
    var result = []; 
    for (var i = 0; i < arr.length; i++) { 
     var el = arr[i]; 
     if (el instanceof Array) result = result.concat(recursiveArraySearch(el, filter)); 
     else filter(el) && result.push(el); 
    } 
    return result; 
} 

// Using it: 
var elements = recursiveArraySearch(all_data, function (el) { return true; });