JS类属性验证函数返回布尔值?

时间:2018-08-12 06:22:07

标签: javascript es6-class

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

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

我想知道的是:这是否是在此上下文中返回真实值的适当方法?有没有更好的方法在JS中进行这种验证?我意识到有other ways会返回一个布尔型的'if'语句,但是我希望这非常简洁,并认为这可能是有效的快捷方式...

2 个答案:

答案 0 :(得分:2)

一样书写
  isValid () {
    return this._id && this._name && true
  }

它将为true值返回truthy,但不会为false值返回falsy

要返回true或false,可以使用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());

答案 1 :(得分:1)

您可以将!!缩写为boolean

return !!(this._id && this._name)
相关问题