我正在尝试遍历嵌套数组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 :(得分: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; });