gpt4 book ai didi

javascript - 搜索短语,循环执行不正确

转载 作者:行者123 更新时间:2023-12-01 04:03:39 25 4
gpt4 key购买 nike

这是上一个问题的更新版本,但它需要不同的答案。

我正在尝试搜索字符串中的短语。

var string = "blahmehfoobar hello random stuff here blahblah blegh coding stackover flow computersc ience";

var textToFind = ["blah", "random stuff", "stackover flow comput"];
var counter = 0;

for (var i = 0; i < textToFind.length; i++){
var text = textToFind[i];
console.log('finding: ' + text);
for (var j = 0; j < string.length; j++){
if (text.charAt(0) === string.charAt(j)){
console.log(string.substring(j, text.length));
if (text === string.substring(j, text.length)){
counter++;
}
}
}
}

console.log(counter);

计数器最后应为 5。

我得到的输出很奇怪:

finding: blah
blah
mehfoo
mehfoobar hello random stuff here
mehfoobar hello random stuff here blah
mehfoobar hello random stuff here blahblah
finding: random stuff

r hello
r hello random stuff he
r hello random stuff here blahblah blegh coding stackove
r hello random stuff here blahblah blegh coding stackover flow compute
finding: stackover flow comput
andom
andom stuff here blahblah blegh coding
andom stuff here blahblah blegh coding stackover flow computer

我不明白为什么在打印第一个找到的短语后执行 string.substring(j, text.length) 。我尝试过调试,但没有成功。

预期输出:

finding: blah
blah
blah
blah
finding: random stuff
random stuff
finding: stackover flow comput
stackover flow comput

编辑:我不是在寻找替代解决方案。我只是想知道为什么循环出错以及为什么我没有得到预期的输出

最佳答案

至于你的代码为什么是错误的?这是因为您正在使用 substring而不是substr .

substr:采用两个参数,一个index,它将作为子字符串开始的 anchor ,以及一个amount(有多少个字符)。

substring:接受两个参数(两个索引,并返回从第一个到最后一个的子字符串)。

关于javascript - 搜索短语,循环执行不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41985746/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com