JavaScript:如何在for循环逻辑中添加else返回'not exist'替代undefined?
解决JavaScript循环中返回'not exist'的问题
你的问题核心是:遍历字符串第2到4位(索引1-3)时,没找到指定字符就返回not exist,但原函数没找到时会返回undefined,而且错误尝试在循环内的if加else导致逻辑不对。
先看原代码的两个问题:
- 第一个
for循环完全冗余:你要检查的是传入的字符y,遍历y的字符最后只保留最后一个,纯多余操作,直接用y即可。 - 函数缺少兜底返回:只有找到匹配时才
return,遍历完所有目标位置都没找到的话,函数自然返回undefined。如果在循环里给if加else,会导致只要当前索引不匹配就立刻返回not exist,根本不会检查剩下的位置,这显然不是你要的效果。
修正后的代码如下:
function check_char(x, y) { // 遍历字符串x的索引1到3(对应第2到4位) for (var i = 1; i <= 3; i++) { const data = x[i]; // 严格匹配字符 if (data === y) { return `${y} exist`; } } // 所有位置都检查完没找到,返回not exist return `${y} not exist`; } document.write(check_char("Python", "y") + "<br>"); document.write(check_char("JavaScript", "a") + "<br>"); document.write(check_char("Console", "o") + "<br>"); document.write(check_char("Console", "C") + "<br>"); document.write(check_char("Console", "e") + "<br>"); document.write(check_char("JavaScript", "S") + "<br>");
运行后输出:
y exist
a exist
o exist
C not exist
e not exist
S not exist
内容的提问来源于stack exchange,提问作者AMRIT SHAHI
相关产品推荐
相关产品推荐

