[英]Using a for-loop to find a string in an array is working, but forEach() does not here. Why and how to correct?
Working through some javascript array exercises to solidify my understanding. 通过一些javascript数组练习来巩固我的理解。 Came across an exercise that I'm able to solve easily using a for-loop, but not using the forEach() method.
进行了一次练习,我可以使用for循环轻松解决问题,但不能使用forEach()方法。 Why is happening, and how would I correct for this?
为什么会发生,我该如何纠正?
Here's the exercise question listed out, and my code using both methods below: "Write a function that takes an array of values and returns an boolean representing if the word "hello" exists in the array." 这是列出的练习问题,我的代码使用下面的两种方法:“编写一个函数,该函数接受一个值数组并返回一个布尔值,表示数组中是否存在单词“ hello”。
function hello_exists(array){ for(i = 0; i < array.length; i++){ if(array[i] === "hello"){ return true } } } var my_arr = ["some", "hello", "is", "cat"] hello_exists(my_arr) // returns true as expected function hello_exists(array){ array.forEach(function(val){ if(val === "hello") { return true } }) } var my_arr = ["some", "hello", "is", "cat"] hello_exists(my_arr) // returns undefined. not sure why?
Returning true
in forEach
does not actually return a value to the caller and has no effect. 在
forEach
中返回true
实际上不会将值返回给调用方,也没有任何作用。
The callback passed into forEach
is designated to perform a set of operations in iteration(without returning anything) 传递给
forEach
的回调被指定为在迭代中执行一组操作(不返回任何内容)
Use a variable to return after the forEach has finished executing 在forEach完成执行之后,使用变量返回
function hello_exists(array){
var exists = false;
array.forEach(function(val){
if(val == "hello"){
exists = true;
}
});
return exists;
}
As an alternative, you can use some() 或者,您可以使用some()
function hello_exists(array){
return array.some(function(val){
return val == "hello";
});
}
or filter() with checking the length
on the results 或filter()并检查结果的
length
function hello_exists(array){
return array.filter(function(val){
return val == "hello";
}).length > 0;
}
Your second hello_exists function is not returning anything. 您的第二个hello_exists函数不返回任何内容。 It may look like it is because you have the 'return' in there, but that is in the forEach function.
可能是因为其中有“ return”,但这在forEach函数中。
In the second example, you need to return something for the hello_exists function. 在第二个示例中,您需要为hello_exists函数返回一些内容。 Something like this would work
这样的事情会起作用
function hello_exists(array){
var isTrue = false
array.forEach(function(val){
if(val === "hello") {
isTrue = true
}
})
return isTrue
}
var my_arr = ["some", "hello", "is", "cat"]
hello_exists(my_arr) // true
It can also help to understand what's happening if you imagine a simplified implementation of forEach
: 如果您想象
forEach
的简化实现,它也可以帮助您了解正在发生的事情:
function forEach(array, fn) {
var i;
for (i = 0; i < array.length; i++) {
fn(arr[i]); // forEach doesn't care about what the function returns
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.