search

Home  >  Q&A  >  body text

javascript - The following code return is inconsistent with imagination, how to solve it?

function has(list, item) {
  list.forEach(v => {
    if (v === item) {
        return true
    }
  })
  return false
}

console.info(has([1,2,3], 1))

How to make the result true???

世界只因有你世界只因有你2752 days ago544

reply all(5)I'll reply

  • 世界只因有你

    世界只因有你2017-05-19 10:45:32

    1. The forEach loop cannot be interrupted
    2. Use for loop
    3. Use indexOf
    4. Use ES6 includes

    reply
    0
  • 过去多啦不再A梦

    过去多啦不再A梦2017-05-19 10:45:32

    forEachThe execution of the method cannot be interrupted and all members will always be traversed
    You can do this

    return list.indexOf(item) !== -1;
    

    or use forloop

    reply
    0
  • 某草草

    某草草2017-05-19 10:45:32

    The arrow function does not have its own this value, but inherits from the surrounding scope.

    reply
    0
  • 高洛峰

    高洛峰2017-05-19 10:45:32

    Actually, it’s not that the questioner doesn’t know how to implement this simple function in other ways, he just uses forEach to do it

    function has(list, item) {
        let flag = false
        list.forEach(v => {
            if (v === item) {
                flag = true
            }
        })
        return flag
    }
    
    console.info(has([1, 2, 3], 1))

    Because forEach's return truereturn false is not the function of return value, so we can only use flag

    reply
    0
  • 黄舟

    黄舟2017-05-19 10:45:32

    function has(list, item){
        var flag = false;
        list.forEach(v => {
            if (v === item) {
                flag = true;
            }
        });
        return flag;
    }
    
    console.log(has([1, 2, 3], 1));
    // true

    reply
    0
  • Cancelreply