首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >选择嵌套数组中的元素

选择嵌套数组中的元素
EN

Stack Overflow用户
提问于 2010-08-27 10:03:09
回答 1查看 1.9K关注 0票数 1

我尝试遍历嵌套的数组var,并选择那些满足单个条件的数组元素。我正在尝试选择所有第一个元素("choice1,choice2...")仅当在"el“中找到"selectedIndex”时才使用内部数组。

例如:如果从下拉列表中选择了"opt2“,则不应选择元素"choice2”和"choice4“,因为该数组中没有”2“,但应获取所有其他元素(choice1,choice3,choice5)。单击here进行演示。在此之前,非常感谢您。

代码语言:javascript
复制
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>
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2010-08-27 10:05:31

在搜索之前,使用递归遍历嵌套数组或展平数组。

代码语言:javascript
复制
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; });
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/3580845

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档