什么时候可以在JavaScript中使用==? [英] When is it OK to use == in JavaScript?

查看:110
本文介绍了什么时候可以在JavaScript中使用==?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

来自: http://www.2ality.com/2011/12/strict-equality-exemptions.html

JavaScript有两个运算符,用于确定两个值是否相等:

JavaScript has two operators for determining whether two values are equal:

  • 严格相等运算符===仅认为具有相同类型的值相等.
  • 普通"(或宽大)的等号运算符==尝试在比较严格等式之前进行转换,以转换不同类型的值.

给JavaScript初学者的建议是完全忽略==,并始终使用===.

The advice given to JavaScript beginners is to completely forget about == and to always use ===.

但是不使用==运算符的原因是什么呢?会导致安全风险吗?

But what is the reason behing it for not using == operator? Will it result to security risk?

但是使用typeof运算符,我们可以确保结果将是字符串.然后==是可以安全使用的,因为我们可以确定它不会执行任何转换手段:

But using typeof operator we can be sure that the result will be a string. Then == is safe to use, because we can be sure that it won’t perform any conversion shenanigans:

if (typeof x == "function") {
    ...
}

推荐答案

根据您的示例,如果您确定它不会执行任何转换诡计",则是,您仍应使用=== ,因为您可以节省解析器的工作量,不必计算是否需要进行转换.这样您将获得更好的性能. (边际,但仍然)

If you're sure that it won't do any "conversion shenanigans", as per your example, then yes, you should still use ===, because you'll save the parser the effort of having to work out whether it needs to do a conversion. So you'll get better performance. (marginal, but still)

这与安全性无关;这与性能和正确执行方式有关.

This isn't about security; it's about performance and about doing things the right way.

您唯一应该使用double equal的地方是您事先知道确实要使用javascript的隐式类型转换的地方.例如,如果您要检查输入字段的数值(可能是字符串),则可能是这种情况.但是即使如此,在很多情况下,最好还是先手动转换该值.

The only time you should use double equal is where you know in advance that you definitely do want to use javascript's implicit type conversion. This might be the case for example if you want to check the numeric value of an input field (which would be string). But even then, in a lot of cases you would be better to convert the value manually first.

简而言之,除非确定需要==的隐式转换功能,否则请在任何地方都使用===语法.

In short, use the === syntax everywhere unless you are certain that you need the implicit conversion functionality of ==.

这篇关于什么时候可以在JavaScript中使用==?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆