1
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}

            )
         }

Chrome JS 调试器工具说:SyntaxError: Unexpected token )

这种语法有什么问题?

4

2 回答 2

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 */ }
            )
         }

您可以使用以下命令使其更具可读性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; };
    }
}
于 2012-05-15T10:45:44.117 回答
4

如前所述,缺少 : 。

但是,这是改进此代码的另一种方法。将操作放在表中(作为对象实现):

var ops = {
  add: function(a, b) {return a + b;},
  mul: function(a, b) {return a * b;},
  sub: function(a, b) {return a - b;},
  div: function(a, b) {return a / b;}
};

然后mathOp执行表查找,如果未找到任何操作,则采取适当的错误处理:

function mathOp(mytype) {
    var op = ops[mytype];
    if(!op) {
        ... error-handling ...
    }
    return op;
}

这样做的好处是操作函数只创建一次而不是每次mathOp调用,它更容易扩展,并且如果需要,该表可以被其他函数使用。

于 2012-05-16T00:50:26.630 回答