简体   繁体   English

如何从传递了参数的回调中返回值

[英]How to return a value from a callback that is passed a parameter

I have made a function square (that returns square of the number)and passed it into another function. 我制作了一个函数平方(返回数字的平方)并将其传递给另一个函数。

var num = 5;
  function square(x){
  return x*x;
}

function display(fn){
  console.log(fn())
}

display(function(){square(num)});

It is not returning me that squared value in display function instead it is returning me 'undefined'. 它不是在显示函数中返回平方值,而是在返回“未定义”。

You don't have to use function(){} to call your function. 您不必使用function(){}来调用函数。 It is only used to define a function. 它仅用于定义功能。

Beside this you can just use the fn variable to log to the console, you don't have to use fn() 除此之外,您可以只使用fn变量登录到控制台,而不必使用fn()

var num = 5;
function square(x){
    return x*x;
}

function display(fn){
    console.log(fn)
}

display(square(num));

It is also possible to return the value into a variable, if this makes it easier to read for you: 也可以将值返回到变量中,如果这样便于您阅读:

function square(x){
    return x*x;
}

function display(fn){
    console.log(fn)
}

var num = 5;
var calculationResult = square(num);
display(calculationResult);

Here. 这里。 You just need to return the square(num) inside the display function. 您只需要在display函数中返回square(num)

 var num = 5; function square(x){ return x*x; } function display(fn){ console.log(fn()); } display(function(){ return square(num); }); 

You lose the returned value here: 您在这里丢失了返回值:

 display(function(){square(num)})

You either have to return it: 您要么必须将其退回:

 display(function(){ return square(num)})

or you use an arrow function 或者您使用箭头功能

 display(() => square(num));

or you bind the function: 或者您绑定函数:

 display(square.bind(null, num));

display(function(){square(num)});

In your code just write return keyword . 在您的代码中只需编写return关键字。

display(function(){return square(num)});

Above code will work fine 上面的代码可以正常工作

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

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