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???
世界只因有你2017-05-19 10:45:32
1. The forEach loop cannot be interrupted
2. Use for loop
3. Use indexOf
4. Use ES6 includes
过去多啦不再A梦2017-05-19 10:45:32
forEach
The 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 for
loop
某草草2017-05-19 10:45:32
The arrow function does not have its own this value, but inherits from the surrounding scope.
高洛峰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 true
和return false
is not the function of return value, so we can only use flag
黄舟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