[英]Print a specific array from within a multi-dimensional array?
所以,我正在试图找出多维数组。
如果我有这个多维数组
var passcodes = [
[1, 4, 4, 1],
[1, 2, 3, 1],
[2, 6, 0, 8],
[5, 5, 5, 5],
[4, 3, 4, 3]
];
如何从中打印出特定的数组? 在这种情况下,没有奇数的那个。 到目前为止,我有这个
for (var i = 0; i < passcodes.length; i++) {
console.log(passcodes[i]);
}
我知道会一次打印出整个阵列,但我无法弄清楚从哪里开始。
看看这种方法。 使用Array#filter迭代外部数组an使用Array#每次得到那些只有奇数的数组。 这将为您提供具有奇数的数组。 然后使用简单的for loop
遍历它们使用它们的索引访问元素。
const passcodes = [ [1, 4, 4, 1], [1, 2, 3, 1], [2, 6, 0, 8], [5, 5, 5, 5], [4, 3, 4, 3] ]; const evenArrays = passcodes.filter(item => item.every(number => number % 2 === 0)); const length = evenArrays.length; for(let i = 0; i < length; i++) { let innerLength = evenArrays[i].length; for(let j = 0; j < innerLength; j++) { console.log(evenArrays[i][j]); } }
在for
声明中引用要处理的数组以在第3个数组上进行迭代,并使用第二个维度来访问其中的元素。
你可以写:
for (var i = 0; i < passcodes[3].length; i++) {
console.log(passcodes[3][i]);
}
你可以找到阵列。
var passcodes = [[1, 4, 4, 1], [1, 2, 3, 1], [2, 6, 0, 8], [5, 5, 5, 5], [4, 3, 4, 3]], result = passcodes.find(a => a.every(b => !(b % 2))); console.log(result);
其中一个更简洁的方法是使用过滤器,请记住,filterPasscodes将遍历passcodes数组,然后filterFunction必须遍历构成passcodes数组的各个数组:
var passcodes = [
[1, 4, 4, 1],
[1, 2, 3, 1],
[2, 6, 0, 8],
[5, 5, 5, 5],
[4, 3, 4, 3]
];
// iterate over each array in passcodes, sending each to the filterFunction
// and returning only those arrays that evaluate to true in the filterFunction
function filterPasscodes(filterFunction) {
return passcodes.filter(filterFunction);
}
如果您只想查找一个特定数组,请使用find方法:
function filterPasscodes(filterFunction) {
return passcodes.find(filterFunction);
}
仅对具有偶数的密码的示例过滤器函数:
// given an array, iterate over each element in that array
// and return only those arrays in which each element is even
function allEven(arr) {
return arr.every(function(element) {
return element === 0 || element % 2 === 0);
});
}
var passcodes = [ [1, 4, 4, 1], [1, 2, 3, 1], [2, 6, 0, 8], [5, 5, 5, 5], [4, 3, 4, 3] ]; //needs to match every item var some = passcodes.map((e) => ( e.some((element, index, array) => element == 2 ) ) ? e : false ).filter(u => u); //needs to match at least one item var every = passcodes.map((e) => ( e.every((element, index, array) => element % 2 ) ) ? e : false ).filter(u => u); console.log(some); console.log(every);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.