首页 > 解决方案 > 从 2 个字符串返回匹配字母的 Js 函数

问题描述

返回用户通过输入类型文本提交的两个字符串中出现的第一个字母的函数,字符串用逗号分隔。例如:aaaaa,bbbbba--> 匹配的字母是 'a',因为两个字符串中都存在

我不确定如何继续,我有一个 for 遍历两个字符串,但我不确定它是否正确

function Ripetizione() {
  var rip = document.getElementById("string").value;
  if (rip.indexOf(",") == -1) { //check to see if the comma is not present
    alert("Non c'è nessuna virgola");
    return;
  }

  var stringa1 = rip.substr(0, rip.indexOf(",")); //this is the string1 before the comma
  var stringa2 = rip.substr(rip.indexOf(",") + 1, rip.length - (stringa1.length + 1)); //this is the second string after the comma

  for (i = 0; i <= stringa1.length; i++) { //for cycle to count the elements of the first string


  }


  for (k = 0; i <= stringa2.lenght; k++) { //same for the string2

  }
}

Ripetizione()

标签: javascript

解决方案


总是更喜欢函数式编程而不是命令式编程。使用Array#find

function getCommonLetter(str){
const [stringA, stringB]=str.split(',');
return Array.from(stringB).find(val => stringA.includes(val));
}

console.log(getCommonLetter('ab,ba'))
console.log(getCommonLetter('ads,bsd'))
console.log(getCommonLetter('aaa,bbc'))


推荐阅读