开发者

ActionScript: Should I always use strict equality ("===")?

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:

be

  • if (param1 === null || param1.length === 0) ?

What about with things like strings? param1 == "This is a String."


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.


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 ===.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜