[英]callback function doesn't return anything
var res = "";
function longest(sen, callback) {
sen = sen.split(" ");
for(var i = 0; i < sen.length; i++) {
callback(sen[i]);
}
}
function findLongest(item) {
if(item.length > res.length) {
res = item;
}
return res;
}
longest("the greatest day EVERERAWEREWRWRAEWR",findLongest);
I'm trying to find the longest word in the string I input, but all it does is return undefined. 我试图在我输入的字符串中找到最长的单词,但它所做的只是返回未定义的值。 I know there's a lot of easier ways to find the longest word, but I want to do it implementing a callback like such.
我知道有很多简单的方法可以找到最长的单词,但是我想实现这样的回调。
longest
updates res
(via the callback) but does not return anything. longest
更新res
(通过回调),但不返回任何内容。 Try printing out res
after your call to longest
, or returning res
from longest
. 呼叫
longest
后尝试打印输出res
,或从longest
后返回res
。
var res = ""; function longest(sen, callback) { sen = sen.split(" "); for(var i = 0; i < sen.length; i++) { callback(sen[i]); } } function findLongest(item) { if(item.length > res.length) { res = item; console.log('now max len is %s',item); } } longest("the greatest day EVERERAWEREWRWRAEWR",findLongest);
remove return,since you don't use it. 删除退货,因为您不使用它。 replace with console.log so you can see result.
替换为console.log,以便查看结果。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.