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???
1. The forEach loop cannot be interrupted2. Use for loop3. Use indexOf4. Use ES6 includes
forEachThe execution of the method cannot be interrupted and all members will always be traversedYou can do this
forEach
return list.indexOf(item) !== -1;
or use forloop
for
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 true和return false is not the function of return value, so we can only use flag
return true
return false
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
1. The forEach loop cannot be interrupted
2. Use for loop
3. Use indexOf
4. Use ES6 includes
forEach
The execution of the method cannot be interrupted and all members will always be traversedYou can do this
or use
for
loopThe 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
Because forEach's
return true
和return false
is not the function of return value, so we can only use flag