为什么第二个 for 循环需要 +i
Why does the second for loop need +i?
我了解所有这些以及它是如何工作的,除了:为什么第二个 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" ]
它之所以做 + i,是因为代码试图将 Eric 的每一次出现从文本推送到 Hits,所以它想要计算 myname.length 字母。这也可以通过 j 从 0 开始并使用 text[j + i]
来实现
i 等于文本中的当前位置。例如
v (i = 5 Starting from 0)
Blah Blah Blah
或
v (i = 6)
Blah Blah Eric Blah
所以 i+name.length 是标记单词的结尾
v->v (i=11 -> i+lenth=14)
Blah Blah Eric Blah
如果你拿+1,你会得到
v<-------v (i=11 -> 1)
Blah Blah Eric Blah
相关文章:
- 第二个循环:跳过
- Vanilla Js:在一个事件中开始一段时间的循环,然后用第二个事件打破它?('mouseover'启
- 数组在 for 循环与第二个 for 循环数组 JavaScript 合并
- 中断语句仅删除第二个循环
- 第二个音频文件意外循环
- 循环遍历数组并成对输出(每个第二个元素的分隔符)
- 使用 ng-if 选择 ng-repeat 循环中的第二个项目
- 为什么第二个 for 循环需要 +i
- React,componentDidUpdate启动第二个操作,陷入循环
- 在Jquery循环幻灯片中添加第二个寻呼机
- 循环遍历对象并在第二个对象javascript中设置为值
- 动画赢得't运行到第二个循环
- 等待循环结束并执行第二个函数
- 循环通过路段标记:在第二个路段后停止
- JavaScript第二个循环没有't更改CSS
- 第一个循环在第二个循环开始时停止
- 为什么我必须添加+ I +到第二个WebElement在Selenium Java循环
- 循环遍历表tr并从第二个td中检索值
- 我怎样才能在不让第一个循环循环到第二个循环的情况下嵌套for循环呢?
- Javascript循环-第二个变量不显示