我已經有一段時間了,但未能達到我想要的結果。我想根據它們的索引比較兩個陣列中的專案。像這樣的東西:
const first = 0;
const second = 1;
const result = []; // should equal (false, true, false)
const final = [[[2,3],[1,1]],[[4,2],[3,0]],[[0,3],[1,1]]];
for (let i = 0; i < final.length; i ) {
for (let j = 0; j < final[i].length; j ){
//Comparison between ((2 and 3) && (1 and 1)) with a single result.
//Should also compare between ((4 and 2) && (3 and 0)) and many other nested arrays
//This logic is not the right one as it can't do the comparison as intended.
if (final[i][j][first] > final[i][j][second]) {
result.push(true);
} else result.push(false);
}
我希望這被理解,足夠了。有一個非常相似的問題。我不知道在這里發布或打開另一個問題是否正確,但它們都很相似。
非常感謝。
uj5u.com熱心網友回復:
你可以試試 :
const first = 0;
const second = 1;
const final = [[[2,3],[1,1]],[[4,2],[3,0]],[[0,3],[1,1]]];
const result = final.map(([e1, e2]) => (e1[first] > e1[second] && e2[first] > e2[second]))
console.log(result)
// with non arrow function
function compareArr(arr, first, second) {
return arr.map(function (ele) {
return ele[0][first] > ele[0][second] && ele[1][first] > ele[1][second]
})
}
console.log(compareArr(final, first, second))
// with non map function :
function compareArr1(arr, first, second) {
let result1 = []
for(let i = 0; i < arr.length; i ) {
result1[i] = true
for(let j = 0; j < arr[i].length; j ) {
if(!(arr[i][j][first] > arr[i][j][second]))
result1[i] = false
}
}
return result1
}
console.log(compareArr1(final, first, second))
更新:編輯@是先生的建議
更新:關于([e1,e2]):
normal :Array.map((ele) => .....)結構為 ele 是[a, b]
它可以使用相同的:Array.map(([a, b]) => .....)
它的檔案:解構分配
uj5u.com熱心網友回復:
Xupitan 使用函式式編程,我認為這是更好的方法,但我嘗試擴展您的代碼。
您之前缺少的是您沒有跟蹤第一個陣列,而是在比較每個嵌套陣列,這種方法也是有效的,但是您需要然后比較每個結果,例如 result[i] && result[i 1] .
const first = 0;
const second = 1;
const result = []; // should equal (true, true, false)
const final = [[[2,3],[1,1]],[[4,2],[3,0]],[[0,3],[1,1]]];
let k=0
for (let i = 0; i < final.length; i ) {
for (let j = 0; j < final[i].length; j ){
//Comparison between ((2 and 3) && (1 and 1)) with a single result.
//Should also compare between ((4 and 2) && (3 and 0)) and many other nested arrays
//This logic is not the right one as it can't do the comparison as intended.
if (final[i][j][first] > final[i][j][second]) {
if(k > 0){
result[i] = true
}
result[i] = true
}else{
//first false exit
result[i] = false;
break;
}
k
}
k=0
}
console.log(result)
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/486087.html
標籤:javascript 数组 嵌套循环
