javascript - 返回布尔值的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”语句的布尔值,但我希望这相当简洁,并认为这可能是一个有效的捷径......
解决方案
当你写它像
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());
推荐阅读
- java - 将 Map 转换为 JSONObject
- screenshot - Direct3D 是否从 GDI32.dll 调用 bitBlt
- python - 不支持的操作数类型:“str”和“str”
- java - JFrame 之间的数据传输
- angular - 模板解析错误 Angular
- google-sheets - 计算数据透视表的统计差异
- leaflet - Leaflet - 允许以高于最大缩放比例切换到另一个基础层
- javascript - 如何使用 Canvas 将我的线条图居中对齐?
- java - 需要构造函数中的 Spring-Boot 通用类型
- asp.net-core - 在提交时从 textarea 值设置 asp-route-content 参数