javascript - 搜索字符串自定义函数算法
问题描述
我想调整我输入值(“ello”)和变量(“hello”)的字符串。
如果在 string("hello") 中找到它,则返回值应该是 "ello"。如果没有找到,返回值应该是-1。
但由于条件(strs[i] == arrayS[tempVal]) ,它返回了 4 次“llll” 。
我怎样才能得到上面提到的正确答案?
var stres = "hello";
var strs = [...stres];
function searchStr(s) {
let arrayS = [...s];
let tempVal = 0;
let tempStr = [];
while (tempVal < arrayS.length) {
for (let i = 0; i < strs.length; i++) {
if (strs[i] == arrayS[tempVal]) {
tempStr.push(arrayS[tempVal]);
}
}
tempVal++;
}
return tempStr;
}
const res = searchStr("ello");
console.log('res', res)
解决方案
根据您的说法,逻辑是正确的,只需在满足条件时打破 for 循环即可。检查下面的代码段和控制台输出。
var stres = "hello";
var strs = [...stres];
function searchStr(s) {
let arrayS = [...s];
let tempVal = 0;
let tempStr = [];
while (tempVal < arrayS.length) {
for (let i = 0; i < strs.length; i++) {
if (strs[i] == arrayS[tempVal]) {
tempStr.push(arrayS[tempVal]);
break;
}
}
tempVal++;
}
return tempStr;
}
const res = searchStr("ello");
const resS = res.join('');
console.log('res = ', res);
console.log('resS = ', resS);
推荐阅读
- azure-devops - Azure 管道检查时间
- python - TraceId 传播
- c# - 您正在尝试解决跨线服务,但在使用 Simple Injector 的活动(Async Scoped)范围之外执行此操作
- python - Python 3 - 避免实例共享或覆盖属性
- android - 法语和西班牙语的 Android 服务调用失败
- node.js - discord.js 使用角色在赠品中查找声明时间
- parsing - 使用 FParsec 解析可能格式错误的输入
- azure - 是否可以使用 az cli 列出所有类型的应用服务
- flutter - 如何在 Flutter 小部件测试中测试导航?
- amazon-web-services - 从 spark 写入 s3 时出现 ProtocolException