简体   繁体   English

如果不返回任何函数,为什么函数返回未定义? Java脚本

[英]Why would a function return undefined if you're not returning anything? Javascript

I have a function like so 我有这样的功能

var tellMeTrueOrFalse = function(collection, callback){
    each(collection, function(item){ 
            console.log((callback(item))?true:false);
        } 
    );
};

( each is a function that behaves like underscore's _.each ). each函数的行为都类似于下划线的_.each )。 But when I try to console.log() the following: 但是,当我尝试console.log() ,以下内容:

tellMeTrueOrFalse([1,2,3], function(x) {return x%2 == 0;})

I get 我懂了

false
true
false
undefined

Why am I getting undefined? 为什么我变得undefined? when I'm not trying to return anything? 当我不尝试退货时? How can I get it to just print and not returned the undefined ? 如何获得仅打印而不返回undefined

Why am I getting undefined? 为什么我变得不确定? when I'm not trying to return anything? 当我不尝试退货时?

you are getting undefined because a function will always return something. 您将变得undefined因为函数将始终返回某些内容。 If there is no explicit return statement, then default value is returned. 如果没有显式的return语句,则返回默认值。 And default value of a function is undefined as per mozilla docs 根据Mozilla文档,函数的默认值是undefined

To return a value other than the default, a function must have a return statement that specifies the value to return. 要返回默认值以外的值,函数必须具有一个return语句,该语句指定要返回的值。 A function without a return statement will return a default value. 没有return语句的函数将返回默认值。 In the case of a constructor called with the new keyword, the default value is the value of its this parameter. 对于使用new关键字调用的构造函数,默认值为其this参数的值。 For all other functions, the default return value is undefined. 对于所有其他功能,默认返回值是未定义的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM