问题
"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