如何在不使用if else语句的情况下最小化代码结构

时间:2018-11-07 20:48:12

标签: javascript

我想问一下是否有更好的方法可以在不使用if else语句的情况下缩小下面的代码。我尝试使用开关盒,但似乎不起作用:

for v in gimp.Vectors

3 个答案:

答案 0 :(得分:8)

我将使用由let express = require('express'); let app = express(); let router = express.Router(); let users = require('./users.js'); let ejs = require('ejs'); let pg = require('pg'); let bodyParser = require('body-parser'); let mysql = require('mysql'); let connection = mysql.createConnection({ host: "localhost", user: "root", password: "password", port: 3306, database: "nodeapp2" }); app.use(bodyParser.urlencoded({ extended: true })); app.get('/input', function(req,res) { res.sendFile(__dirname + '/views/input.html'); }); app.get('/login', function (req,res) { res.sendFile(__dirname + '/views/login.html'); }); app.post('/logincred', function(req, res) { console.log('req.body'); console.log(req.body); connection.query("SELECT password FROM logins WHERE password = '"+req.body.password+"'",function(err, result){ if (err) throw err; if (result[0].password === req.body.password){ console.log(req.body.password); console.log('password accepted'); res.redirect('/'); res.end() } else { res.redirect('/login') res.write('login failed'); res.end() } }); }); 索引的对象,该对象的值是相关的数字:

inputValueTime

对于不在对象中的const times = { thirty: 1800000, fourtyFive: 2700000, oneHour: 3600000, oneHalf: 5400000, oneQuarter: 6300000, twoHours: 7200000 }; function foo(inputValueTime) { return times[inputValueTime]; } ,这将返回undefined,就像您的原始代码一样,在大多数情况下, -如果inputValueTime可以具有inputValueTime属性(例如Object.prototype),然后也使用'isPrototypeOf'检查。

答案 1 :(得分:0)

为什么您说 switch 子句不起作用?看代码

function sample(inputValueTime) {
  switch (inputValueTime) {
    case 'thirty':
      return 1800000;
    case 'fortyFive':
      return 2700000;
    case 'oneHour':
      return 3600000;
    case 'oneHalf':
      return 5400000;
    case 'oneQuarter':
      return 6300000;
    case 'twoHours':
      return 7200000;
    default:
      return -1;
  }
}

console.log(sample("thirty"));
console.log(sample("fortyFive"));
console.log(sample("oneHour"));
console.log(sample("oneHalf"));
console.log(sample("oneQuarter"));
console.log(sample("twoHours"));

答案 2 :(得分:0)

您应该可以使用switch语句。

function (inputValueTime) {
  switch (inputValueTime) {
    case 'thirty':
      return 1800000
    case 'fortyFive':
      return `270000
    case 'oneHour':
      return 3600000
    case 'oneHalf':
      return 5400000
    case 'oneQuarter'
      return 6300000
    case 'twoHours':
      return 7200000
  }
}