我在这个函数/嵌套循环中哪里搞错了



我是JS的新手,经常做这些挑战来学好JS。

我在这里尝试使用嵌套循环,并尝试创建一个函数,该函数应返回不在schoolsA中的schoolsB数组中的值,因此我想要的预期输出是:

"Edify", "Beacon House"

我想我已经达到了if-else的一半,但相反,它只返回两个数组中存在的值,不管我想要什么!

我试过这样做:

if (!(arr2[i].includes(arr1[j]))) {

但这也没用!

我哪里搞错了?

附言:我知道我可以简单地使用过滤方法来实现我想要的,但我也想学会使用它!

let schoolsA = ["Aman", "Shoeby", "Rose"];
let schoolsB = ["Aman", "Shoeby", "Edify", "Beacon House"];
function filtering(arr1, arr2) {
let output = [];
for (let i = 0; i < arr2.length; i++) {
for (let j = 0; j < arr1.length; j++) {
if (arr2[i].includes(arr1[j])) {
output.push(arr2[i]);
}
}
}
return output;
}
console.log(filtering(schoolsA, schoolsB));

也许你想要这样的:

function filtering(arr1, arr2) {
let output = [];
// iterate over every element in arr2
for (let i = 0; i < arr2.length; i++) {
// If arr1 does not include the element arr2[i], then add it to the output
if (!arr1.includes(arr2[i])) {
output.push(arr2[i]);
}
}
return output;
}

let schoolsA = ["Aman", "Shoeby", "Rose"];
let schoolsB = ["Aman", "Shoeby", "Edify", "Beacon House"];
function filtering(arr1, arr2) {
let output = [];
for (let element of arr2) {
if (!arr1.includes(element)) {
output.push(element);
}
}
return output;
}
console.log(filtering(schoolsA, schoolsB));

相关内容

  • 没有找到相关文章