如何运行第二个程序

时间:2019-02-13 11:19:50

标签: javascript arrays function object ecmascript-6


  1. -开始代码段:js隐藏:false控制台:true babel:false->

    var运算符= {'+':function(a,b){return a + b},'-': function(a,b){return a-b},'*':function(a,b){return a

    • b},'/':function(a,b){     返回a / b   } };

    var op ='/'; console.log(operators [op](10,10)); //工作正常

    var运算符= [{'+':function(a,b){return a + b},'-': function(a,b){return a-b},'*':function(a,b){return a * b},'/':function(a,b){return a / b}}]; var op ='/';

    l请帮助我...如何运行第二个程序

2 个答案:

答案 0 :(得分:1)

为此,您应该使用find()

console.log(operators.find(e => Object.keys(e).includes(op))[op](10, 10));

ES5:

console.log(operators.find(function(e) {
    return Object.keys(e).indexOf(op) > -1;
})[op](10, 10));

答案 1 :(得分:0)

您也可以使用开关盒

function calculate(a,b,op) {
 switch (op) {
  case '+':
    return a + b;
    break;
  case '-':
    return a - b;
    break;
  case '*':
    return a * b;
    break;
  case '/':
    return a / b;
    break;
 default: 
    return "No operator found";
}
}
var op = '+'
calculate(5,5,'op')