javascript - The following code return is inconsistent with imagination, how to solve it?
世界只因有你
世界只因有你 2017-05-19 10:43:32
0
5
537
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???

世界只因有你
世界只因有你

reply all(5)
世界只因有你

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

过去多啦不再A梦

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

某草草

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

小葫芦

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

黄舟
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
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template