首页 > 解决方案 > 返回布尔值的JS类属性验证函数?

问题描述

我有一个 es6 模型,我想在它发布到端点之前对其进行一些基本验证。我在类上写了一个简单的 isValid() 方法,我想返回真或假,而不是真假。由于 && 将返回最后一个真实的检查,因此我通过将&& true附加到验证检查的末尾来缩短函数。

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

我想知道的是:这是在这种情况下返回真实值的合适方法吗?有没有更好的方法在 JS 中进行这种验证?我意识到还有其他方法可以返回执行“if”语句的布尔值,但我希望这相当简洁,并认为这可能是一个有效的捷径......

标签: javascriptes6-class

解决方案


当你写它像

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

它将返回true一个truthy值,但不会返回false一个falsy值。

为了返回真或假,您可以使用Boolean构造函数,如

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());


推荐阅读