我在这里看到一些非常奇怪的东西,我无法弄清楚。我试图返回一个逗号分隔的字符串,其中包含strArr
元素中出现的数字。
您将在传递给FindIntersection
的自变量["1, 2, 4, 5, 6, 9", "2, 3, 4, 8, 10"]
中看到2
出现在两个数组中,但在filter
{{1中找不到}}测试。谁能解释一下?
includes
答案 0 :(得分:2)
数组1中的每个元素都有一个前导空格,因此您需要在比较它们之前对它们进行修整。
const FindIntersection = (strArr) => {
const strArrOne = strArr[0].split(',').map(x => x.trim())
const strArrTwo = strArr[1].split(',').map(x => x.trim())
const intersection = strArrOne.filter(item => {
return strArrTwo.includes(item)
}).join(',').replace(/\s/g, '');
console.log(intersection)
return intersection;
}
console.log(FindIntersection(["1, 2, 4, 5, 6, 9", "2, 3, 4, 8, 10"]));
答案 1 :(得分:0)
第一个数组元素中2
之前有一个多余的空格,您需要删除其中包含===
用来检查是否存在的空格
const FindIntersection = (strArr) => {
const strArrOne = strArr[0].split(',').map(s=> s.replace(/\s/g,''))
const strArrTwo = strArr[1].split(',').map(s=> s.replace(/\s/g,''))
const intersection = strArrOne.filter(item => {
console.log('2',strArrTwo)
console.log('item --> ', item)
console.log('includes ---> ', strArrTwo.includes(item))
return strArrTwo.includes(item)
}).join(',').replace(/\s/g, '');
console.log(intersection)
return intersection;
}
console.log(FindIntersection(["1, 2, 4, 5, 6, 9", "2, 3, 4, 8, 10"]));
答案 2 :(得分:0)
删除空格是最简单的解决方法
const FindIntersection = (strArr) => {
const strArrOne = strArr[0].split(',')
const strArrTwo = strArr[1].split(',')
const intersection = strArrOne.filter(item => {
console.log('2',strArrTwo)
console.log('item --> ', item)
console.log('includes ---> ', strArrTwo.includes(item))
return strArrTwo.includes(item)
}).join(',').replace(/\s/g, '');
console.log(intersection)
return intersection;
}
console.log(FindIntersection(["1,2,4,5,6,9", "2,3,4,8,10"]));
答案 3 :(得分:0)
由于期望数组中的第一个项目,其他项目在数字之前有空格。要解决此问题,您可以映射所有项目以将项目转换为如下所示的数字:
const FindIntersection = strArr => {
const strArrOne = strArr[0].split(",").map(item => Number(item));
const strArrTwo = strArr[1].split(",").map(item => Number(item));
const intersection = strArrOne
.filter(item => {
console.log("2", strArrTwo);
console.log("item --> ", item);
console.log("includes ---> ", strArrTwo.includes(item));
return strArrTwo.includes(item);
})
.join(",")
.replace(/\s/g, "");
console.log(intersection);
return intersection;
};
console.log(FindIntersection(["1, 2, 4, 5, 6, 9", "2, 3, 4, 8, 10"]));