【问题标题】:How to avoid Switch case on input values [duplicate]如何避免在输入值上切换大小写[重复]
【发布时间】:2018-10-03 12:52:29
【问题描述】:

我问自己一个问题来优化我的 JavaScript 代码。 我目前正在做这样的事情:

数据.json:

{
  "House" :
    { "bedroom"  : "4" }
    { "kitchen"  : "1" }
    { "bathroom" : "2" }
}

选择.js:

var Data = require('./Data.json');

printData = function(id) {
  console.log(getData(id));
}

getData = function(id) {
  switch (id) {
    case "bedroom":
      return Data.House.bedroom;
    case "kitchen":
      return Data.House.kitchen;
    case "bathroom":
      return Data.House.bathroom;
    default:
      break;
  }
}

我想知道我们是否可以使用特殊的语法对其进行优化,例如,如果我们只是有:

var Data = require('./Data.json');

printData = function(id) {
  console.log(Data.House.{ id });
}

我知道这对您来说可能是一个愚蠢的问题,但如果您告诉我这是否可能,将会很有帮助。我希望我可以避免在我的项目中使用很长的 Switch Case。

谢谢。

【问题讨论】:

  • return Data.House[id]

标签: javascript json function optimization switch-statement


【解决方案1】:

你可以做到的:

var Data = {
  "House" : { 
    "bedroom"  : "4", 
    "kitchen"  : "1",
    "bathroom" : "2" 
  }
};

getData = function(id) {
  return Data.House[id];
}

console.log(getData('bedroom'));
console.log(getData('kitchen'));
console.log(getData('xxx'));

【讨论】:

    【解决方案2】:

    使用[] 表示法

    printData=function(id){
        return Data.House[id];
    }
    

    【讨论】:

      【解决方案3】:
      getData=function(id){
         if(Data.House.hasOwnProperty(id)) return Data.House[id];
          return '';
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-11-07
        • 1970-01-01
        • 1970-01-01
        • 2021-07-27
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多