JavaScript:有条件检查的快捷方式语法



说我的函数需要检查与两个不同值之一的匹配。但是,输入非常复杂:

function checker(id, value){
  if (this.state.users[id].items[value].name === 'onething ' ||
    this.state.users[id].items[value].name === 'theotherthing ' ){
    // my action
  }
}

我最终要做的是:

function checker(id, value){
  var name = this.state.users[id].items[value].name
  if (name === 'onething ' || name === 'theotherthing '){
    // my action
  }
}

有什么办法可以做这样的事情:

function checker(id, value){
  if (this.state.users[id].items[value].name === 'onething ' || 'theotherthing '){
    // my action
  }
}

显然,第二种方法比第一个方法更容易打字,并且更容易重构。他们如何比较内存/速度明智?

您可以使用Array#indexOf并针对-1

进行测试
if (['onething ', 'theotherthing '].indexOf(this.state.users[id].items[value].name ) !== -1){

在ecmascript 2016中,您可以做类似:

的事情
if (['onething ','theotherthing'].includes(this.state.users[id].items[value].name)) {
    //do stuff
}

该语句由以下部分组成:

  1. if语句(显然)

  2. 数组定义: ['onething ','theotherthing']

  3. 在先前定义的数组上调用方法includes()

在JavaScript中,数组是具有与任何其他对象一样具有方法的对象。其中一种方法是includes(),它检查该参数是否包含在数组内部。此方法的返回类型是布尔值,因此它是由IF语句直接评估的,而无需任何铸造

更多关于includes()方法的信息

您可以使用对象符号:

if (this.state.users[id].items in {"onething ":1, "theotherthing ":1}){

或正则表达式也可以工作 - 较短,但效率较低:

if (/onething |theotherthing /.test(this.state.users[id].items)){

最新更新