这个高阶函数有什么问题?

Amo*_*kar 1 javascript higher-order-functions

mathOp =  function(type){
            return (
               "add" == type?  function(a,b){return a + b}
              :"mul" == type?  function(a,b){return a * b}
              :"sub" == type?  function(a,b){return a - b}
              :"div" == type?  function(a,b){return a / b}

            )
         }
Run Code Online (Sandbox Code Playgroud)

Chrome JS调试工具说:SyntaxError:意外的令牌)

这个语法有什么问题?

Thi*_*ter 5

你忘记了最后: else一部分.

mathOp =  function(type){
            return (
               "add" == type?  function(a,b){return a + b}
              :"mul" == type?  function(a,b){return a * b}
              :"sub" == type?  function(a,b){return a - b}
              :"div" == type?  function(a,b){return a / b}
              : function() { return NaN; /* or throw an exception */ }
            )
         }
Run Code Online (Sandbox Code Playgroud)

您可以使用以下内容使其更具可读性switch():

function mathOp(type) {
    switch(type) {
        case 'add': return function(a,b) { return a + b; };
        case 'mul': return function(a,b) { return a * b; };
        case 'sub': return function(a,b) { return a - b; };
        case 'div': return function(a,b) { return a / b; };
    }
}
Run Code Online (Sandbox Code Playgroud)