【问题标题】:strings from array contain common substring javascript数组中的字符串包含公共子字符串 javascript
【发布时间】:2019-10-25 16:22:50
【问题描述】:

这是我的代码: 我想遍历数组的每一对元素,如果每对中的字符串包含一个或多个公共子字符串,console.log(true),否则console.log(false)。 所以,输出应该是truefalse,因为“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);

提前感谢您的回答!

【问题讨论】:

  • 你能举一个常见的子字符串的例子,比如 first 和 student 在其中有 st 常见。这是你的意思还是它是完整的字符串,还是你的意思是字符
  • 您只是将两个测试字符串中的相同字符位置与if (a1.charAt(i) == a2.charAt(i)) 进行比较,因此“first”和“criss”唯一的共同点是位置 4(3 ,如果你从 0 开始计数。)

标签: javascript


【解决方案1】:

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));

【讨论】:

  • 如何使用return代替console.log?
  • 返回不是结果数组,而是内联“true”,然后是“false”
  • 您可以使用 , 加入数组。查看更新的答案
【解决方案2】:

您可以使用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);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-05-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多