函数作为参数

参数作为方法名,执行方法
 
 
function add(x,y){return x+y}
function subtract(x,y){return x-y}
function multiply(x,y){return x*y}
function divide(x,y){return x/y}
 
function operate(operateor, operand1, operand2){
return operateor(operand1, operand2);
}
 
var i = operate(add, operate(add, 2, 3), operate(multiply, 4, 5));
console.log(i);
 
console.log("===============");
 
var operateors = {
add: function(x, y){return x+y},
subtract: function(x,y){returnx-y},
multiply: function(x,y){returnx*y},
divide: function(x,y){returnx/y},
pow:Math.pow
};
 
function operate2(operation, operand1, operand2){
if(typeof operateors[operation] === 'function'){
return operateors[operation](operand1, operand2);
}
}
 
var j = operate2("add", "hello", operate2("add", " ", "world"));
console.log(j);
console.log(operate2("pow", 10, 2));
 

posted @ 2019-04-20 16:27  _dafeng  阅读(129)  评论(0编辑  收藏  举报