JS弱类型语言的优势——之模板字符串

  ES6中,开始支持模板字符串。

  尽管Java和C#这样的高级语言有非常多吸引人的地方,但是想js这样的弱类型语言,也有独到之处。

  equType:有四种类型,分别是:chl、chwp、cwp、cot,后端java接口提供了四个接口,四个接口对应四个函数调用,每一个函数名的规则是[equType]Control,
let equDetailService = {*/
  chlControl: function(params) {
    return request.post(url.coldStation.equDetail.chlControl, params);
  },
  //冷冻泵启停接口
  chwpControl: function(params) {
    return request.post(url.coldStation.equDetail.chwpControl, params);
  },
  //冷却泵启停接口
  cwpControl: function(params) {
    return request.post(url.coldStation.equDetail.cwpControl, params);
  },
  //冷却塔启停接口
  cotControl: function(params) {
    return request.post(url.coldStation.equDetail.cotControl, params);
  }
};

  前端同一个组件在四个不同的页面中使用,组件对应的equType值不同,根据equType值不同要调用后端不同的接口。

   axios的js调用:

      equDetailService[`${this.equType}Control`](serachObj).then(res => {
        if (res.code === 200) {
         //执行成功
        }
      });

  后端一个详情页面的接口返回一个Json对象,如下数据:

detailInfo:{G1_COT1_ON/OFF: "0.0",
G1_COT1_VFD_ON/OFF: "1.0",
G1_COT1_FRQ: "30.0",
G1_COT1_FRQ_SET: "50.0",
G1_COT1_PWR: "5.0",
G1_COT1_PWR_deviceId: 95
G1_COT1_VFD_PWR: "5.0",
G1_COT1_VFD_PWR_deviceId: 95
G1_COT1_VFD_ALM: "0.0",
G1_COT1_PWR_ALM: "0.0",
G1_COT1_PWR_ALM_deviceId: 95,
G1_COT1_REM/LOC: "1.0",
G1_COT1_HRS: "5300.0",
G1_COT1_EN/DIS: "1.0",
G1_COT1_RANK: "0.0",
G1_COT1_PWR_FRQ: "0.0",
G1_COT1_PWR_FRQ_deviceId: 95,
G1_COT1_FRQ_HAND/AUTO: "0.0",
G1_COT2_ON/OFF: "0.0",
G1_COT2_VFD_ON/OFF: "1.0",
G1_COT2_FRQ: "30.0",
G1_COT2_FRQ_SET: "50.0",
G1_COT2_PWR: "5.0",
G1_COT2_PWR_deviceId: 96,
G1_COT2_VFD_PWR: "5.0",
G1_COT2_VFD_PWR_deviceId: 96,
G1_COT2_VFD_ALM: "0.0",
G1_COT2_PWR_ALM: "0.0",
G1_COT2_PWR_ALM_deviceId: 96,
G1_COT2_REM/LOC: "1.0",
G1_COT2_HRS: "5437.0",
G1_COT2_EN/DIS: "1.0",
G1_COT2_RANK: "0.0",
G1_COT2_PWR_FRQ: "--",
G1_COT2_PWR_FRQ_deviceId: 96,
G1_COT2_FRQ_HAND/AUTO: "0.0",
G1_COT3_ON/OFF: "0.0",
G1_COT3_VFD_ON/OFF: "1.0",
G1_COT3_FRQ: "30.0",
G1_COT3_FRQ_SET: "50.0",
G1_COT3_PWR: "5.0",
G1_COT3_PWR_deviceId: 97,
G1_COT3_VFD_PWR: "5.0",
G1_COT3_VFD_PWR_deviceId: 97,
G1_COT3_VFD_ALM: "0.0",
G1_COT3_PWR_ALM: "0.0",
G1_COT3_PWR_ALM_deviceId: 97,
G1_COT3_REM/LOC: "1.0",
G1_COT3_HRS: "5436.0",
G1_COT3_EN/DIS: "1.0",
G1_COT3_RANK: "0.0",
G1_COT3_PWR_FRQ: "--",
G1_COT3_PWR_FRQ_deviceId: 97,
G1_COT3_FRQ_HAND/AUTO: "1.0",
}

  G1是组名,groupNumber会变化,

  而前端又是一个组件,好几个页面用,只调用一个接口,接口返回的是个Json对象,而不是一个数组,但是前端界面又要显示三个tab,进行数据绑定时,又可以用到模板字符,以取G1_COT1_FRQ_SET这个字符为例,vue数据绑定:

{{detailInfo[`${groupNumber}_COT${index+1}_FRQ_SET`]}}

  直接可以把detailInfo中的数据拆分为3项。

  Java有的语法糖,JS有,Java没有的语法糖,JS还是有,这就是它的强大之处。

  总结:模板字符在有些时候可以避免if else和正则表达式校验,类似于后端语言的反射(如C#)。注:一些高级语言的反射非常耗性能。

你可能感兴趣的:(JS弱类型语言的优势——之模板字符串)