Ju6*_*aut 1 javascript jquery operators
我确信我在这里缺少一些JavaScript基础知识,但任何人都可以帮助我理解为什么这些评估方式不同?最后一行.
$("input[name=myGroup]").click(function () {
if ($(this).is(":checked")) {
if ($(this).val() != "Customers") { //do the stuff...
Run Code Online (Sandbox Code Playgroud)
和
$("input[name=myGroup]").click(function () {
if ($(this).is(":checked")) {
if (!$(this).val() == "Customers") { //do the stuff
Run Code Online (Sandbox Code Playgroud)
在我的特定实例中,我认为他们都会评价为真,并"做那些东西".但似乎只有第一个块实际上是根据我的想法进行评估.
在查看MDN之后,尝试深入了解比较运算符https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Expressions_and_Operators#Comparison_operators 与使用逻辑运算符https:// developer. mozilla.org/en-US/docs/Web/JavaScript/Guide/Expressions_and_Operators#Comparison_operators但我仍然不太明白他们为什么会产生不同的结果.谢谢.
操作顺序很重要.!是以前==,所以
!$(this).val() == "Customers"
Run Code Online (Sandbox Code Playgroud)
被视为
false == "Customers"
Run Code Online (Sandbox Code Playgroud)
false当然,它会返回.尝试使用
!($(this).val() === "Customers")
Run Code Online (Sandbox Code Playgroud)
相反:注意明确的括号.我还使用了严格相等运算符(===而不是==),因此也比较了类型.
当然,只是使用
$(this).val() !== "Customers"
Run Code Online (Sandbox Code Playgroud)
工作完美,并且是最可读的.
| 归档时间: |
|
| 查看次数: |
162 次 |
| 最近记录: |