【问题标题】:Javascript: shortcut syntax for conditional check?Javascript:条件检查的快捷语法?
【发布时间】:2017-03-14 19:03:21
【问题描述】:

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

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

显然第二种方法比第一种方法需要更少的输入并且更容易重构。他们如何比较内存/速度?

【问题讨论】:

  • 像我一样的第三个 ide,但不适用于 javascipt

标签: javascript syntax shortcut


【解决方案1】:

您可以使用Array#indexOf 并针对-1 进行测试

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

【讨论】:

  • 或者一个简单的正则表达式,但我相信不是他想要的
  • 这只适用于数组吗?看起来您的答案缺少 .name 部分。 (我只是为这个问题编了一个例子,我正在寻找普遍适用的东西)
  • @Life4ants,对,这部分丢失了,但你明白了这个模式。您可以将所有字符串放入数组中并使用 indexOf 进行检查。
【解决方案2】:

在 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()方法here

【讨论】:

  • 我最喜欢这个答案,尽管它与@nina 的答案基本相同,只是使用新的 ES6 .includes。您能否编辑它以向初学者解释它在做什么以及它是如何工作的?
  • 我试试看
【解决方案3】:

你可以使用对象表示法:

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

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

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

【讨论】:

    猜你喜欢
    • 2015-06-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-10
    • 1970-01-01
    • 2014-10-22
    • 2012-12-13
    相关资源
    最近更新 更多