为何满足条件时React中的if/else语句仍执行else分支?
问题:React中检查电影标题匹配时循环未停止且执行else分支
你的代码问题出在循环内部的逻辑设计:
- 每遍历一个电影条目,只要当前条目和输入值不匹配,就会立刻执行
else分支的打印语句; - 就算找到了匹配的条目,循环也不会停止,还会继续遍历剩下的电影,后面不匹配的条目依然会触发
else的提示。
修正方案
把逻辑改成:找到匹配项后终止循环,且仅当整个循环结束都没找到匹配时,才提示“未找到”。修改后的func函数如下:
const func = (arg) => { let found = false; // 标记是否找到匹配项 for(let i = 0; i < movies.length; i++){ if(arg === movies[i].title){ console.log(movies[i].title) console.log(`The movie ${movies[i].title} has been found`) found = true; break; // 找到后立刻终止循环 } } // 循环结束后判断是否未找到 if(!found){ console.log(`The movie ${arg} has not been found!`) } }
更简洁的写法(用数组find方法)
可以用数组的find方法替代for循环,代码更简洁易读:
const func = (arg) => { const matchedMovie = movies.find(movie => movie.title === arg); if(matchedMovie){ console.log(matchedMovie.title) console.log(`The movie ${matchedMovie.title} has been found`) } else { console.log(`The movie ${arg} has not been found!`) } }
额外优化(可选)
如果想忽略大小写匹配(比如输入batman: the dark knight也能匹配),可以把条件改成:
movie.title.toLowerCase() === arg.toLowerCase()
内容的提问来源于stack exchange,提问作者Vuyi
相关产品推荐
相关产品推荐

