我有一个 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”语句的 bool 值,但我希望它相当简洁,并认为这可能是一个有效的快捷方式...
最佳答案
当你这样写时
isValid () {
return this._id && this._name && true
}
对于 truthy
值,它将返回 true
,但对于 falsy
值,它不会返回 false
。
为了返回 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());
关于javascript - JS 类属性验证函数返回 bool 值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51806281/