JSClass属性验证函数哪个returnsboolean?

JS Class property validation function which returns boolean?

我有一个 es6 模型,我想在将其发布到端点之前对其进行一些基本验证。我在 class 上写了一个简单的 isValid() 方法,我想 return 是真还是假,不是真,是假。由于 && 将 return 最后一次检查是否为真,我通过将 && true 附加到验证检查的末尾来简化函数。

export default class foo {
  constructor (data = {}) {
    this._id = data.id
    this._name = data.name
  }
  isValid () {
    return this._id && this._name && true
  }
}

我想知道的是:在这种情况下,这是 return 真实价值的合适方式吗?有没有更好的方法在 JS 中进行这种验证?我意识到有 到 return 一个布尔值执行 'if' 语句,但我希望它相当简洁,并认为这可能是一个有效的快捷方式...

当你这样写的时候

  isValid () {
    return this._id && this._name && true
  }

它将 return true 用于 truthy 值,但不会 return false 用于 falsy 值。

为了return真或假,可以使用Boolean构造函数like

isValid () {
    return Boolean(this._id && this._name)
  }

否则你可以使用三元运算符

isValid () {
    return this._id && this._name? true : false
  }

演示片段:

class foo {
  constructor (data = {}) {
    this._id = data.id
    this._name = data.name
  }
  isValid () {
    return Boolean(this._id && this._name)
  }
}

let foo1 = new foo({ id: 1, name: 'abc'});
let foo2 = new foo({ id: 2 });

console.log(foo1.isValid(), foo2.isValid());

您可以 shorthand !! 转换为 boolean

return !!(this._id && this._name)