这是我的代码:
我想遍历数组的每一对元素,并且如果每对中的字符串包含一个或多个公共子字符串console.log(true)
,否则为console.log(false)
。
因此,输出应为true
,false
,因为“ first”和“ criss”具有共同的子字符串(“ r”,“ i”,“ s”)
这是我现在的代码;
const a = ["first", "hi"];
const b = ["criss", "student"];
function commonSubstring(a, b) {
a.forEach(a1 =>
b.forEach(a2 => {
for (i = 0; i < a1.length; i++) {
if (a1.charAt(i) == a2.charAt(i)) {
console.log(true");
}
}
})
);
}
commonSubstring(a, b);
感谢提前答复!
答案 0 :(得分:0)
您可以使用Set
并检查字符是否常见。
function common(a, b) {
return [...a].some(Set.prototype.has, new Set(b));
}
var a = ["first", "hi"],
b = ["criss", "student"],
result = a.map((v, i) => common(v, b[i]));
console.log(result);
答案 1 :(得分:0)
const a = ["first", "hi"];
const b = ["criss", "student"];
function commonSubstring(a, b) {
let result = [];
a.forEach(a1 => {
let found = false;
b.forEach(a2 => {
for (i = 0; i < a1.length; i++) {
if (a1.charAt(i) == a2.charAt(i)) {
//console.log(true);
found = true;
}
}
})
result.push(found);
//console.log(found)
});
return result.join(',');
}
console.log(commonSubstring(a, b));