Javascript 下面的代码使用lastIndexOf方法。为什么代码在到达=0的位置后,开始无限打印F?
Javascript 下面的代码使用lastIndexOf方法。为什么代码在到达=0的位置后,开始无限打印F?,javascript,Javascript,让str=“时间过得飞快,就好像有一样”; 让target=“as”; pos=str.长度; 而((pos=str.lastIndexOf(target,pos-1))!=-1){ 控制台日志(pos); if(pos==0)break;//为什么对此进行注释会导致无限循环? }以下是lastIndexOf的参数说明: Parameter Description item The item to search for start
让str=“时间过得飞快,就好像有一样”;
让target=“as”;
pos=str.长度;
而((pos=str.lastIndexOf(target,pos-1))!=-1){
控制台日志(pos);
if(pos==0)break;//为什么对此进行注释会导致无限循环?
}
以下是lastIndexOf的参数说明:
Parameter Description
item The item to search for
start Where to start the search. Negative values will start
at the given position counting from the end, and search to
the beginning
参数描述
要搜索的项目
从何处开始搜索。负值将开始
在给定位置从末端开始计数,并搜索到
开头
str.lastIndexOf(target,-1)
基本上是一个indexOf
,因此第一次出现在0处
无需向您显示工作代码,因为您已经得到:当位置为0时退出循环 我的观点是正确的,我的上一个答案(删除以避免混淆)没有考虑到
pos
值的更新,但是有了这一点,答案是非常明显的
pos
的最后一个值为0。在下一个循环中,计算值为lastIndex(target,-1)
,当您要求从位置-1开始搜索时,该值将始终为0。这是因为在上一次迭代中pos
始终设置为0
,因此0!=1
始终计算true,循环运行infinitely@palash为什么总是设置为0
?这是因为lastIndexOf(searchValue[,fromIndex])
方法返回调用字符串对象中指定值最后一次出现的索引,从索引向后搜索,仅当未找到值且str
中存在目标时,才会返回-1
。。因此,即使fromIndex
<0,值始终为0。此处,fromIndex
是可选的,它是字符串中最后一个字符的索引,被视为匹配的开始。默认值为+无限
。如果fromIndex>=str.length
,则搜索整个字符串。如果索引<0
中的,行为将与索引为0时的行为相同。为什么仅为0
?我的目标位于pos=0
。但是在达到该值之后,pos
为什么没有变为负值,即pos=-1
?