试图解决这个问题,但我不知道我的错误在哪里!
function findIntersection(strArr) {
const arr1 =[strArr[0]];
const arr2 = [strArr[1]];
const finalArr =[];
arr1.forEach(e=>{arr2.forEach(element => {
if(element === e){
finalArr.push(e);
console.log(true)
}
})})
}
findIntersection(['1, 3, 4, 7, 13', '1, 2, 4, 13, 15']); // => '1,4,13'
findIntersection(['1, 3, 9, 10, 17, 18', '1, 4, 9, 10']); // => '1,9,10'
发布于 2020-12-06 06:45:38
您有各种错误,包括没有将字符串拆分到数组中,不必要地将其包装在数组中,以及没有返回finalArr。
function findIntersection(strArr) {
const arr1 = strArr[0].split(", ");
const arr2 = strArr[1].split(", ");
const finalArr = [];
arr1.forEach(el1 => {
arr2.forEach(el2 => {
if (el1 === el2) {
finalArr.push(el1);
}
});
});
return finalArr;
}或者,对集合使用更快的解决方案:
function findIntersection(strArr) {
const arr1 = new Set(strArr[0].split(", "));
const arr2 = strArr[1].split(", ");
return arr2.filter(el => arr1.has(el));
}发布于 2020-12-06 06:44:06
问题在于您是如何对数据建模的。传入的参数应该是一个包含两个整数数组的数组,而您有一个包含两个字符串数组。如果必须处理包含两个字符串的数组,则必须提取这两个字符串,然后使用String.split()将它们转换为数组。
function findIntersection(strArr) {
const arr1 = strArr[0]
const arr2 = strArr[1]
const finalArr = [];
arr1.forEach(el1 => {
arr2.forEach(el2 => {
if (el2 === el1) {
finalArr.push(el1);
}
})
})
return finalArr
}
const res1 = findIntersection([[1, 3, 4, 7, 13], [1, 2, 4, 13, 15]]); // => '1,4,13'
const res2 = findIntersection([[1, 3, 9, 10, 17, 18], [1, 4, 9, 10]]); // => '1,9,10'
console.log(res1, res2)
https://stackoverflow.com/questions/65162682
复制相似问题