Javascript 数组forEach不返回布尔值

Javascript 数组forEach不返回布尔值,javascript,function,return-value,Javascript,Function,Return Value,有人能告诉我为什么前两个函数返回未定义而不是布尔值吗 forEach始终返回未定义的return.forEach将始终导致返回未定义的,无论forEach中的逻辑如何。如果要检查数组中的任何项是否通过特定测试,则应使用。而不是使用部分: const数组1=[1,2,3]; 常量test1Result=test1(); console.log(test1Result); 函数test1(){ 返回数组1.some(x=>2==x); }forEach返回未定义。您希望在案例中使用的是array

有人能告诉我为什么前两个函数返回未定义而不是布尔值吗


forEach
始终返回
未定义的
return.forEach
将始终导致返回
未定义的
,无论
forEach
中的逻辑如何。如果要检查数组中的任何项是否通过特定测试,则应使用
。而不是使用部分

const数组1=[1,2,3];
常量test1Result=test1();
console.log(test1Result);
函数test1(){
返回数组1.some(x=>2==x);

}
forEach返回未定义。您希望在案例中使用的是array.includes

const数组1=[1,2,3];
函数test1(){
返回阵列1。包括(2);
}
常量test1Result=test1();
console.log(test1Result)如果选中“检查返回值”部分,它将返回未定义

Foreach没有任何返回类型,您可以使用。若您必须使用foreach,那个么您可以像我在
test2

const数组1=[1,2,3];
常量test1Result=test1();
const test2Result=test2();
const test3Result=test3();
console.log(test1Result);
console.log(test2Result);
日志(test3Result);
函数test1(){
返回数组1.some(x=>2==x);
}
函数test2(){
var=false;
数组1.forEach((x,索引)=>{
如果(2==x){
发现=真;
}
});
发现退货;
}
函数test3(){
常量maybeTeam=array1.find(x=>2==x);
返回(maybeTeam)?真:假;
}
解释

当函数中没有显式返回时。默认情况下,javascript函数返回该函数的
未定义的

参考一下下面的例子。这里内部
console.log('hello')
正在打印
hello
,但由于从内部
console.log()返回隐式返回值
undefined
所以外部
console.log()
打印
undefined

console.log(console.log('Hello'))
不返回特殊值,具体取决于回调函数的内部返回值。它只是迭代所有项目

或者它的对应项提前返回,这取决于回调的返回值


在使用ES6时,如果传递的值是数组的一部分,则可以使用返回布尔值的

const数组1=[1,2,3];

console.log(array1.includes(2));//true
forEach返回未定义
const array1 = [1, 2, 3];

const test1Result = test1();
const test2Result = test2();
const test3Result = test3();

console.log(test1Result);
console.log(test2Result);
console.log(test3Result);


function test1() {
    return array1.forEach(x => 2 === x);
}

function test2() {
    const found = array1.forEach((x, index) => {
        if (2 === x) {
            return true;
        }
        return false;
    });

    return found;
}

function test3() {
    const maybeTeam = array1.find(x => 2 == x);

    return (maybeTeam) ? true : false;
}