JavaScript逻辑或操作员在函数的返回语句中
我正在使用Vuetify,特别是从内部V形式的V-Text-Field。这些V-Text-Field中的每一个都有一个名为“规则”的属性,用于验证。该属性接受具有一堆功能的数组。这是我偶然发现了一个怪异的代码的地方:
(title) => !!title || "Title is required"
因此,想法是,此函数从输入中获取值,如果长度等于0,则错误消息“必需的标题”是显示。我的问题是:此功能实际返回什么?
I am using Vuetify, specifically the v-text-field from inside v-form. Each of these v-text-fields has a property called rules, used for validation. That property accepts an array with a bunch of functions. This is where I've stumbled over a weird-ish piece of code:
(title) => !!title || "Title is required"
So, the idea is that this function gets the value from the input, and if the length is equal to 0, then the error message "Title is required" is shown. My question is: what does this function actually return?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
让我们将其分解
为...首先,箭头功能只是:
接下来,
!!
是双重否定的,实际上只是逻辑上不是opperator 两次。第一个否定将数据(无论是数据类型)转换为布尔值。第二个否定再次改变了布尔值,以给出所需的结果。例如
!!'Hello'
- >true
,!! 0
- >false
,!! UNDEFINED
- >false
下一部分是比较。
||
是或opperator ,因此,如果上半年是True/Prange,则将返回||
后的零件,将返回。例如
true || '一些文本'
将返回true
,wherasfalse || '一些文本'
将返回一些文本
这里有一些示例,尝试运行摘要以查看输出
这不是最好的代码,因为它不太清楚,而且您通常不想混合这样的类型。它还没有检查标题是否是有效的类型,因此
123
或true
将被接受为有效。Let's break it down...
To start with, the arrow function is just shorthand for:
Next, the
!!
is a double negation, effectively just the logical not opperator twice. The first negation converts the data (whatever it data type it may be) to a boolean. The second negation changes the boolean again to give the desired result.E.g.
!!'hello'
-->true
,!!0
-->false
,!!undefined
-->false
The next part is a comparison. The
||
is OR opperator, so if the first half is true / present, then it will be returned, if not, the part after the||
will be returned.E.g.
true || 'some text'
will returntrue
, wherasfalse || 'some text'
will returnsome text
Here are some example, try running the snippet to see the outputs
It's not the best code, because it's not super clear, and you usually don't want to mix types like this. It also doesn't check if the title is a valid type, so
123
ortrue
would be accepted as valid.