gpt4 book ai didi

javascript - 如果您没有返回任何内容,为什么函数会返回未定义? JavaScript

转载 作者:行者123 更新时间:2023-11-28 18:48:47 25 4
gpt4 key购买 nike

我有一个像这样的函数

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

(each 是一个行为类似于下划线的 _.each 的函数)。但是当我尝试 console.log() 时,出现以下内容:

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

我明白了

false
true
false
undefined

当我没有尝试返回任何内容时,为什么会出现undefined??我怎样才能让它只打印而不返回未定义

最佳答案

Why am I getting undefined? when I'm not trying to return anything?

你会得到未定义,因为函数总是会返回一些东西。如果没有明确的 return 语句,则返回默认值。根据mozilla docs,函数的默认值为未定义

To return a value other than the default, a function must have a return statement that specifies the value to return. A function without a return statement will return a default value. In the case of a constructor called with the new keyword, the default value is the value of its this parameter. For all other functions, the default return value is undefined.

关于javascript - 如果您没有返回任何内容,为什么函数会返回未定义? JavaScript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34870350/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com