JavaScript 三个数组元素循环匹配检查?
JavaScript three array elements match-check by loops?
不确定如何正确设置循环以检查目标数组中的元素是否匹配任何两个其他数组或同时匹配它们:
代码:
let test = [1,2,3,4,5,6,7]
let test2 = [7,8,9,10,11]
let check_test = [2,7,10,12]
for (var testa in test) {
for (var test2a in test2) {
for (var check_testa in check_test) {
#Triple for-loop trying to loop all arrays
if (check_testa == testa && check_testa != test2) {
console.log("Match TEST")
} else if (check_testa != testa && check_testa == test2) {
console.log("Match TEST2")
} else if (check_testa == testa && check_testa == test2) {
console.log("Both match!")
} else {
console.log("None match!")
}
}
}
}
基本上代码应该检查数组 check_test
中的元素是否与其他两个数组 test
和 test2
.
中的任何元素匹配
如果 check_test
的元素仅与其他两个数组之一中的元素匹配,则打印“匹配 [test] 或 [test2]!”。如果两者匹配,则打印“Both Match!”最后,如果两者都不匹配,则打印“None 匹配!”
这个输出应该是:
2 Match TEST!
7 Both Match!
10 Match TEST2!
12 None Match!
那么如何正确设置循环使其匹配检查然后打印元素并只输出一次?感谢阅读。
您不需要嵌套循环。使用 .includes
来检查被迭代的值存在于哪个其他数组中(如果有的话),以及 don't use in
when iterating over arrays(如果你要使用 in
,至少访问中的值带括号符号的数组,而不是仅使用索引)。
let test1 = [1,2,3,4,5,6,7];
let test2 = [7,8,9,10,11];
let check_test = [2,7,10,12];
for (const num of check_test) {
const one = test1.includes(num);
const two = test2.includes(num);
if (one && two) {
console.log('both');
} else if (!one && !two) {
console.log('neither');
} else if (one) {
console.log('one');
} else {
console.log('two');
}
}
不确定如何正确设置循环以检查目标数组中的元素是否匹配任何两个其他数组或同时匹配它们:
代码:
let test = [1,2,3,4,5,6,7]
let test2 = [7,8,9,10,11]
let check_test = [2,7,10,12]
for (var testa in test) {
for (var test2a in test2) {
for (var check_testa in check_test) {
#Triple for-loop trying to loop all arrays
if (check_testa == testa && check_testa != test2) {
console.log("Match TEST")
} else if (check_testa != testa && check_testa == test2) {
console.log("Match TEST2")
} else if (check_testa == testa && check_testa == test2) {
console.log("Both match!")
} else {
console.log("None match!")
}
}
}
}
基本上代码应该检查数组 check_test
中的元素是否与其他两个数组 test
和 test2
.
如果 check_test
的元素仅与其他两个数组之一中的元素匹配,则打印“匹配 [test] 或 [test2]!”。如果两者匹配,则打印“Both Match!”最后,如果两者都不匹配,则打印“None 匹配!”
这个输出应该是:
2 Match TEST!
7 Both Match!
10 Match TEST2!
12 None Match!
那么如何正确设置循环使其匹配检查然后打印元素并只输出一次?感谢阅读。
您不需要嵌套循环。使用 .includes
来检查被迭代的值存在于哪个其他数组中(如果有的话),以及 don't use in
when iterating over arrays(如果你要使用 in
,至少访问中的值带括号符号的数组,而不是仅使用索引)。
let test1 = [1,2,3,4,5,6,7];
let test2 = [7,8,9,10,11];
let check_test = [2,7,10,12];
for (const num of check_test) {
const one = test1.includes(num);
const two = test2.includes(num);
if (one && two) {
console.log('both');
} else if (!one && !two) {
console.log('neither');
} else if (one) {
console.log('one');
} else {
console.log('two');
}
}