我应该使用布尔(值)还是可以直接比较?
我在本文中写下了这种情况:
if (title && content){
// code
}
但是后来我看到了这个示例:
const canSave = Boolean(title) && Boolean(content) && Boolean(userId)
他们使用cansave
在按钮中传递到残疾人道具。
使用Boollean而不是仅仅执行以下操作是最好的做法吗?
const canSave = title && content && userId
在什么情况下,我应该使用boolean()?
I usally write this kind of conditions:
if (title && content){
// code
}
But then I see this example:
const canSave = Boolean(title) && Boolean(content) && Boolean(userId)
And they used canSave
to pass in to disabled prop in a button.
Is it a best practice to use Boollean instead of just doing the following?
const canSave = title && content && userId
In what cases should I use Boolean()?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
布尔函数的主要目标是将值转换为布尔值,在您的情况下,在分配到变量之前转换为布尔值很有意义,因为如果您尝试这样做:
变量
cansave
将分配userId
的值并将忽略其余部分,但是如果将值转换为布尔值,则变量cansave
将分配这些值之间比较的结果。使用布尔函数的另一个原因可能是在将值传递给仅接受布尔作为参数的函数之前转换一个值,就像这样:在这种情况下,将值转换为布尔是有意义的,也许另一种情况是在之前转换值保存到数据库。由于正面数字,字符串,数组和对象之类的值始终是 true ,零或负数,空字符串,未定义和null是 false ,有些情况没有像在有条件的语句中一样,将其转换为有意义:
这些变量将被铸造为布尔值,因此将其转换为您的代码只会在您的代码中创建冗余。
The main goal of Boolean function is to convert a value to boolean, in your case makes sense to convert to boolean before assign to a variable because if you try to do it that way:
the variable
canSave
will assign the value ofuserId
and will ignore the rest, but if you convert the values to boolean, the variablecanSave
will assign the result of a comparison between these values. Another reason to use the boolean function could be to convert a value before pass it to a function who only accepts boolean as parameters, like so:In this case makes sense to convert the value to boolean, maybe another case would be convert the value before saving to a database. As values like positive numbers, strings, arrays and objects are always true and zero or negative numbers, empty strings, undefined and null are false, there's some cases that doesn't make sense to convert it, like in a conditional statement, like so:
These variables will be casts to a boolean already, so converting it will just create redundancy in your code.