javascript - 从 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()
解决方案
总是更喜欢函数式编程而不是命令式编程。使用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'))
推荐阅读
- node.js - 运行节点应用程序时带有环境变量的 Docker CMD
- haskell - 如何在 Hakyll html 中为第二个帖子目录创建第二个列表?
- css - 为什么在尝试将我的 Angular 项目从基于 CSS 的项目转换为 SCSS 项目时出现此错误?
- django - 为前端图片渲染创建一个“虚拟”URL 路径
- postgresql - 按日期划分的范围分区,其中一个分区用于 NULL 日期
- directus - 如果将“多对多”字段添加到 directus_users
- javascript - 如何对齐 HTML5 表单验证气泡消息?
- vue.js - 使用组件通过 CDN 读取条码
- reporting-services - SSRS 电子邮件订阅的条件页脚
- r - 如何在 R 中构建这个 JSON 文件?