gpt4 book ai didi

javascript - 为什么第二个for循环需要+i?

转载 作者:行者123 更新时间:2023-12-02 16:48:33 24 4
gpt4 key购买 nike

我了解所有这些及其工作原理,除了:为什么第二个 for 循环需要“+i”?为什么不能用“+1”代替?

text = "Blah blah blah blah blah blah Eric
blah blah blah Eric blah blah Eric blah blah
blah blah blah blah blah Eric";

var myName = "Eric";
var hits = [];

// Look for "E" in the text
for(var i = 0; i < text.length; i++) {
if (text[i] === "E") {
// If we find it, add characters up to
// the length of my name to the array
for(var j = i; j < (myName.length + i); j++) {
hits.push(text[j]);
}
}
}

if (hits.length === 0) {
console.log("Your name wasn't found!");
} else {
console.log(hits);
}

最佳答案

j 循环偏移 i

i 从 0 到 text.length,例如从 0 到 100。

每当找到 "E" 时,j 就会从 i 循环到 i + myName.length,因此例如从 50 到 54。

您还可以让 j 从 0 循环到 myName.length 并执行 text[j + i]

<小时/>

请注意,此代码实际上并不是查找 "Eric",而是查找 "E",然后记录接下来的 4 个字符。如果您的输入字符串是 "EaEbEc foo" 您的结果将是 [ "EaEb", "EbEc", "Ec f"]

关于javascript - 为什么第二个for循环需要+i?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26896447/

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