简体   繁体   English

什么时候在 Javascript 中使用双重相等(松散相等)有意义?

[英]When does it make sense to use double equality (loose equality) in Javascript?

Given the type coercion and the performance issue , as a JS newbie, I've always tried to avoid using double equality and opted for triple equality instead.鉴于类型强制性能问题,作为一个 JS 新手,我一直试图避免使用双重相等,而是选择了三重相等。

However, when does it make sense to use double quality?但是,什么时候使用双重质量才有意义?

When you want to allow Javascript to convert types automatically.当您希望允许 Javascript 自动转换类型时。 Eg例如

if (someElement.value == 3)

value of an input is always a string. value的输入的始终是一个字符串。 The == operator will automatically convert it to a number here, so you don't have to write ==操作符会在此处自动将其转换为数字,因此您不必编写

if (parseInt(someElement.value) === 3)

You should be careful, since some some of the automatic conversions may not do what you expect.您应该小心,因为某些自动转换可能无法达到您的预期。

Short answer: it never makes sense to use == instead of === .简短回答:使用==而不是===永远没有意义。

Long answer: while it never makes sense, there are cases where you want to write less code, and you are sure about your input.长答案:虽然它永远没有意义,但在某些情况下,您希望编写更少的代码,并且您对自己的输入很确定。

== is not that bad if you really understand what's truthy.如果你真的理解什么是真实的, ==并没有那么糟糕。 There are some gotchas, for example [1] == true and [2] == false .有一些问题,例如[1] == true[2] == false

Remember that the principal aim of Javascript was to be an easy language to be used by web designers, that's one of the reasons behind all this stuff you encounter.请记住,Javascript 的主要目标是成为一种易于Web 设计人员使用的语言,这就是您遇到所有这些东西的原因之一。

As a simple example, as Barmar said , the best approach is to use it to avoid converting data and check equality.作为一个简单的例子,正如Barmar 所说,最好的方法是使用它来避免转换数据和检查相等性。 Here is another example:这是另一个例子:

const deleteTodos = _ => {
    if (howManyTasksToRemoveInput.value == tasks.length) {
        warningLabel.innerHTML = "You can't remove all the list";
    } else if (howManyTasksToRemoveInput.value > tasks.length) {
        warningLabel.innerHTML = "You DEFINITELY can't remove more tasks than you have";
    } else {
        tasks.splice(0, +howManyTasksToRemoveInput.value);
    }
}

There's one case where there's a clear benefit to using == , which is foo == null : this is true if and only if foo === undefined || foo === null在一种情况下,使用==明显的好处,即foo == null :当且仅当foo === undefined || foo === null foo === undefined || foo === null , a commonly useful test. foo === undefined || foo === null ,一个常用的测试。

Even here, using something like node's isNullOrUndefined(foo) (which is implemented as return value == null; !) is a much clearer way to express the intent, if it's not an established practice in the code-base you're working in.即使在这里,使用像 node 的isNullOrUndefined(foo) (它被实现为return value == null; !)是一种更清晰的表达意图的方式,如果它不是你正在使用的代码库中的既定做法.

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM