简体   繁体   English

在JavaScript中使用===进行字符串比较是否有意义?

[英]Does it make sense to use === for string comparison in JavaScript?

While it's clear how using the === operator for eg numbers is useful ( 0 , null and undefined all being falsy values, which can lead to confusion), I'm not sure if there are benefits to using === for string comparisons. 虽然很明显如何使用===运算符作为数字是有用的( 0nullundefined都是假值,这可能导致混淆),我不确定使用===进行字符串比较是否有好处。

Some of my team mates use this operator for all comparisons, but does it really make sense? 我的一些队友使用这个操作符进行所有比较,但它真的有意义吗? Is there at least some minor performance impact? 是否至少有一些轻微的性能影响?

If you know the types are the same, then there's no difference in the algorithm between == and === . 如果你知道类型是相同的,那么=====之间的算法没有区别。

That said, when I see == , I assume that I'm using it for its type coercion, which makes me stop and analyze the code. 也就是说,当我看到== ,我认为我正在使用它来进行类型强制,这使我停止并分析代码。

When I see === I know that there's no coercion intended, so I don't need to give it a second thought. 当我看到===我知道没有强制意图,所以我不需要再考虑一下。

In other words, I only use == if I intend for there to be some sort of type coercion. 换句话说,我只使用==如果我打算那里有某种类型的强制。

It is considered good practice to always use === for comparisons in JavaScript. 在JavaScript中使用===进行比较被认为是一种好习惯。 Since JavaScript is a dynamic language, it is possible that what you think are two strings could be variables with different types. 由于JavaScript是一种动态语言,因此您认为两个字符串可能是不同类型的变量。

Consider the following: 考虑以下:

var a = "2", b = 2;
a == b  // true
a === b // false

The only way to guarantee a false result in this case would be to use === when comparing the two values. 在这种情况下保证false结果的唯一方法是在比较两个值时使用===

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 什么时候在 Javascript 中使用双重相等(松散相等)有意义? - When does it make sense to use double equality (loose equality) in Javascript? 在前端 javascript 应用程序中使用 DI 容器是否有意义 - Does it make sense to use DI container in front end javascript app 在JavaScript块上使用HTML注释仍然有意义吗? - Does it still make sense to use HTML comments on blocks of JavaScript? 在学习Javascript时,软件开发人员使用jQuery是否有意义? - Does it make sense for software developer to use jQuery when learning Javascript? 将Web Workers用于游戏是否有意义? - Does it make sense to use Web Workers for a game? 在$ watch回调中使用$ scope是否有意义? - Does it make sense to use $scope into a a $watch callback? 尝试协助JavaScript垃圾收集器是否有意义? - Does it make sense to attempt to assist the JavaScript Garbage Collector? 在Java 8 Nashorn JavaScript引擎中同时加载脚本是否有意义 - Does it make sense to load scripts concurrently in Java 8 Nashorn JavaScript engine 这个 Webhost 奇怪的 Javascript 解释有意义吗? - Does This Webhost's Odd Javascript-Explanation Make Sense? 在提交之前用javascript加密密码是否有意义? - does it make sense to encrypt a password in javascript before submit?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM