Javascript:条件检查的快捷语法?

Javascript: shortcut syntax for conditional check?

假设我有一个函数需要检查是否与两个不同值之一匹配。但是,输入很复杂:

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
  }
}

显然,第二种方法比第一种方法需要更少的输入,并且更容易重构。他们如何比较 memory/speed 明智?

在 ECMAScript 2016 中,您可以执行以下操作:

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

该语句由以下部分组成:

  1. if 语句(显然)

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

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

在 javascript 中,数组是一种对象,它与任何其他对象一样具有方法。其中一种方法是 includes(),它检查参数是否包含在数组中。此方法的 return 类型是布尔值,因此它直接由 if 语句计算,无需任何转换

更多关于 includes() 方法 here

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

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

您可以使用对象表示法:

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

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

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