1、if
语句
var num1 = 10, num2 = 20, op = '+'; if (op === '+') { var result = num1 + num2; console.log(result); } else if (op === '-') { var result = num1 - num2; console.log(result); } else if (op === '*') { var result = num1 * num2; console.log(result); } else if (op === '/') { var result = num1 / num2; console.log(result); } else { console.log('请输入正确的操作符'); }
2、switch
语句
var num1 = 10, num2 = 20, op = '+'; switch (op) { case "+": console.log(num1 + num2); break; case "-": console.log(num1 - num2); break; case "*": console.log(num1 * num2); break; case "/": console.log(num1 / num2); break; default: console.log('请输入正确的操作符'); break; }
3、条件运算符(简写的if语句)
var num1 = 10, num2 = 20, op = '+'; var result = num1 > num2 ? "num1大于num2" : "num1小于或等于num2"; console.log(result);