[英]Iterating over array to check whether strings ```includes``` another string
using the includes
method to check whether strings in an array include another string.使用includes
方法检查数组中的字符串是否包含另一个字符串。 Basically like a search function type of thing.基本上就像搜索 function 类型的东西。
Heres what I have so far这是我到目前为止所拥有的
this.findIngredient = function(ingredientName) {
for (i=0; i < this.ingredients.length; i++) {
if (this.ingredients[i].includes(ingredientName)) {
return true
break
} else {
return false
}
}
}
what im unsure about is why when the this.ingredient
does hold a string that includes ingredientName
it still outputs false
.我不确定的是为什么当this.ingredient
确实包含一个包含ingredientName
的字符串时它仍然输出false
。
For context this is the this.ingredient
array对于上下文,这是this.ingredient
数组
this.ingredients = ["500g plain flour", "1 tsp fine salt", "2 heaped tsp baking powder"]
Removing the else block from within your loop should resolve the issue.从循环中删除 else 块应该可以解决问题。
Explanation -解释 -
The else block is run when this.ingredients[i].includes(ingredientName)
is false
. else 块在this.ingredients[i].includes(ingredientName)
为false
时运行。 And in your code, when the else block returns false
which means your loop will not have the opportunity to check every element in the ingredients array since the function will stop execution when it sees a return statement.在您的代码中,当 else 块返回false
时,这意味着您的循环将没有机会检查成分数组中的每个元素,因为 function 在看到 return 语句时将停止执行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.