Using a function as a parameter to another function

Deadly 提交于 2019-12-25 01:33:33

问题


"use strict";
function square(x) {
    return x * x;
}
function add(square,y) {
    return square(4) +y
    document.write(square + y)
}
add(4,1);
console.log(add(4,1));

I have to use a function as in the parameter of another function. I am trying to output 17.


回答1:


Just call it as such:

add(square,1);

you may also want to change

function add(square,y) {
    return square(4) +y
    document.write(square + y)
}

to be:

function add(square,y) {
    document.write(square(4) + y)        
    return square(4) +y
}

Per Andrew's comment, it might also be a good choice to change document.write calls to be console.log and open the browser console to read results.




回答2:


Probably easier to visualize if you change the argument name in your function declaration to be more generic but also more identifiable as a function requirement.

The name you use here is not relevant to the name of the function you will actually pass in

function add(func, num) {
    document.write(func(4) + num);
    return func(4) + num;    
}

add(square,1);

Then in another call you might do

add(myOtherCalcFunction, 6);


来源:https://stackoverflow.com/questions/39885804/using-a-function-as-a-parameter-to-another-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!