ActionScript:我应该始终使用严格相等(“===”)吗?
我想知道在进行相等性检查时是否应该始终使用“===”(严格相等)...是否有任何例子说明何时最好使用“==”(非严格平等)?特别是,应该:
if (param1 == null || param1.length == 0)
为
if (param1 === null || param1.length === 0)
代码>?
那么像字符串这样的东西呢? param1 ==“这是一个字符串。”
I'm wondering if I should always use "===" (strict equality) when doing equality checks... Is there any example of when it is preferable to use "==" (non-strict equality)? In particular, should:
if (param1 == null || param1.length == 0)
be
if (param1 === null || param1.length === 0)
?
What about with things like strings? param1 == "This is a String."
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
应使用的运算符取决于您的需要。
“==”检查两个值在转换为相同数据类型后是否相等(如果可能)。因此,“5”== 5 为真,因为字符串“5”被转换为数字,然后进行检查,显然 5 实际上等于 5
。“===”检查两个值是否类型相同且相等。因此,“5” === 5 将计算为 false,因为 1 是字符串,1 是数字。
在用途选择方面,归结为期望。如果您希望比较的两个值具有相同类型,那么您应该使用“===”。但是,如果它们可以是不同的类型,并且您希望比较自动执行转换(例如,将字符串 5 与数字 5 进行比较),则可以使用“==”。
在您的示例中,所有这些都应该可以使用“==”运算符,但为了增加类型安全性,您当然可以使用“===”运算符。例如,我倾向于专门检查空值。
希望这有帮助。
The operator that should be used depends on your needs.
The "==" checks if two values are equal after they've been converted to the same datatype (if possible.) So, "5" == 5 would be true, because the string "5" is converted to a number, and then the check is made, and obviously 5 does in fact equal 5.
The "===" checks if two values are the same type AND equal. So, "5" === 5 would evaluate to false because one is a string and one is a number.
In terms of choice of use, it comes down to expectations. If you expect the two values your comparing to be of the same type, then you should use "===". However, if they can be of different types and and you want the comparison to perform the conversion automatically (e.g., comparing a string 5 to a number 5), then you can use "==".
In the case of your examples, all of them should be fine with the "==" operator, but for added type safety, you certainly can use the "===" operator. I tend to specifically check for nulls, for instance.
Hope this helps.
我实际上不太了解 ActionScript,但我相信它符合 EMCAScript,这意味着我的 JavaScript 知识是相关的。
在 JavaScript 中,如果您愿意接受显式类型(这意味着永远不要执行
"something" + 5
,请始终在类型中显式显示,例如"something" + String(5)
"something" + String(5) code>),如果您采用这种方法,实际上永远不会出现 == 优于 === 的情况。I don't actually know much about ActionScript, but I believe it's EMCAScript compliant which means my JavaScript knowledge would be relevant.
In JavaScript, if you're willing to embrace explicit typing (this means never do
"something" + 5
, always be explicit in your types e.g."something" + String(5)
), if you embrace that approach there's actually never an instance where == is preferred to ===.