gpt4 book ai didi

javascript - 比较操作 - 正确的语法?

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:19:24 25 4
gpt4 key购买 nike

来自 PHP,我理解在比较操作中使用 == 和 === 的区别,但是对于 JavaScript,使用 == 或 === 是否可以接受?

我想验证我的 JavaScript 代码并找到了 JSLint .在使用 JSLint 运行验证时,我看到了这些类型的消息。

一些例子:

var show = $('input[name=female]:checked').val() == "true";
  • 第 278 行第 70 个字符的问题:应为“!==”,但看到的却是“!=”。

var show = $('input[name=living]:checked').val() != "false";
  • 第 283 行第 38 个字符的问题:应为“!==”,但看到的却是“!=”。

所以我的问题是,使用 == 或 != 的当前语法是否有效/正确,还是我需要使用 === 和 !== ?

编辑:只是为了指出代码确实有效

最佳答案

这在某种程度上是正确的,但 JSLint 期望进行严格的比较以防止类型转换出现问题。

最好只在您真正需要/想要的地方使用严格比较和“正常”比较(因为出于某种原因您想使用类型转换)。

来自 JSLint 的 documentation :

== and !=

The == and != operators do type coercion before comparing. This is bad because it causes ' \t\r\n' == 0 to be true. This can mask type errors.

If you only care that a value is truthy or falsy, then use the short form. Instead of

(foo != 0)

just say

(foo)

and instead of

(foo == 0)

say

(!foo)

Always use the === and !== operators.

关于javascript - 比较操作 - 正确的语法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5487381/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com