![](/img/trans.png)
[英]See if an array contains all the number from other nested arrays with JavaScript?
[英]JavaScript: Use forEach to see if array contains a specific number value
我有下面的代码。 我故意在这种情况下尝试使用forEach。
function check(arr, el) {
arr.forEach((element) => {
console.log(element)
if (element === el) {
return true
}
})
}
check([1, 2, 3, 4, 5], 3)
我期望代码返回true,因为3的el值在数组中。 但是相反,它返回未定义。 我究竟做错了什么?
function check(arr, el) { return arr.some( element => element === el) } console.log(check([1, 2, 3, 4, 5], 3))
如果要使用forEach
使用变量存储值,然后再从函数返回
function check(arr, el) { let found = false arr.forEach((element) => { if (element === el && !found){ found = true } }) return found } console.log(check([1, 2, 3, 4, 5], 3))
无法在forEach
语句中使用return
。
注意:此答案仅是因为您需要使用forEach
。 通常,您将始终使用some()
。
function check(arr, el) { let found = false; arr.forEach((element) => { console.log(element) if (element === el) { found = true; } }); return found; } console.log( check([1, 2, 3, 4, 5], 3));
只是为了使用OP的上下文。 因为必须使用forEach。
function check(arr, el) {
let found = false;
arr.forEach((element) => {
console.log(element)
if (element === el){
found = true;
}
})
return found;
}
如果要使用forEach
,则需要在找到匹配项时更新变量。 默认情况下, Array.forEach返回undefined
。 有没有build in
的方式来摆脱的foreach 。
由于您只是在寻找简单的元素匹配项,因此只需使用Array.includes
:
let check = (arr, el) => arr.includes(el) console.log(check([1, 2, 3, 4, 5], 3))
Array.some为您提供了迭代器函数,在这种情况下,您实际上不需要。
使用Array.forEach
:
function check(arr, el) { let result = false arr.forEach((element) => { if (element === el) { result = true // <-- update the result on match } }) return result // <-- return the result } console.log(check([1, 2, 3, 4, 5], 3))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.