简体   繁体   English

使用for循环在数组中查找字符串是可行的,但是forEach()在此无效。 为什么以及如何纠正?

[英]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.

相关问题 如何使用 forEach() 复制这个 for 循环? - How to replicate this for-loop using forEach()? 在这里将c#转换为javascript。 -JavaScript将字符串更改为数组 - convert c# to javascript here. - javascript change string to array 使用+ =求和在这里不起作用。 为什么? - Getting sum using += doesn't work in here. Why? 如何在 react/javascript For-Loop & ForEach 中访问对象数组中的属性? - How to access properties in array of objects in react/javascript For-Loop & ForEach? 使用数组和for循环的JavaScript轮播:为什么slideIndex在第一个循环后被“卡住”? - JavaScript carousel using array and for-loop: Why does slideIndex get “stuck” after first loop? 我如何使该函数递归并在这里删除for in循环。 我通过使用此功能获得Maark,Maary等的结果 - how could i make this function recursive and remove the for in loop here. where i get the result of Maark, Maary etc by using this function 当for循环使用一个对象数组时,forEach不起作用 - forEach not working when for loop does with an array of objects 为什么我的for循环返回正确的答案,但我的forEach没有? - Why does my for loop return the correct answer, but my forEach does not? 为什么输出0在这里。 var a = 7; a.constructor(); - Why is the output 0 here. var a = 7; a.constructor(); 在这里变得未定义。 有什么理由吗? - Getting undefined here. Any reason why?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM