简体   繁体   English

JavaScript 中的 (var1 !== var2) 与 (var1 && var1 !== var2) 有什么区别?

[英]What is the difference between (var1 !== var2) vs (var1 && var1 !== var2) in JavaScript?

What is the difference between (var1 !== var2) vs (var1 && var1 !== var2) in JavaScript? JavaScript 中的(var1 !== var2)(var1 && var1 !== var2)什么区别?

The above question is in reference to when working with HTMLElementObjects as variables.上面的问题是在使用 HTMLElementObjects 作为变量时参考的。

Google Chrome's extension development example shows this in the below function: Google Chrome 的扩展程序开发示例在以下函数中显示了这一点:

  let current = event.target.parentElement.querySelector(
    `.${selectedClassName}`
  );
  if (current && current !== event.target) {
    current.classList.remove(selectedClassName);
  }

  let color = event.target.dataset.color;
  event.target.classList.add(selectedClassName);
  chrome.storage.sync.set({ color });
}

Why does it have to be "current && current"?为什么它必须是“当前&&当前”? It doesn't work with just "current !== event.target"它不适用于“当前!== event.target”

Link to full article for reference: https://developer.chrome.com/docs/extensions/mv3/getstarted/#logic全文链接供参考: https : //developer.chrome.com/docs/extensions/mv3/getstarted/#logic

This is because of JavaScript's operator precedence :这是因为 JavaScript 的运算符优先级

11: Strict Inequality ( !== ) 11: 严格不等式 ( !== )
... ...
7: Logical AND ( && ) 7:逻辑与( &&

Since strict inequality has a higher precedence than logical AND, it's functionally equivalent to the following:由于严格不等式比逻辑 AND 具有更高的优先级,因此它在功能上等效于以下内容:

(current) && (current !== event.target)

The people who wrote the tutorial likely did not want this expression to evaluate as true if current was any kind of falsey value.如果current是任何类型的 falsey 值,编写教程的人可能不希望这个表达式被评估为 true。 By doing this, they ensure that event.target can't just be any old value and still pass.通过这样做,他们确保event.target不能只是任何旧值并且仍然通过。

What it does is checks if current is truthy AND is not equal to event.target.它的作用是检查电流truthy,并不等于event.target。 If event.target and current are both null it will still return false如果 event.target 和 current 都是 null,它仍然会返回 false

The first Var checking in var && var... is checking if var is not null or undefined and then compare It with var2 In fact, you could write It like that : var && var...的第一个 Var 检查是检查 var 是否不为空或未定义,然后将它与 var2 进行比较实际上,您可以这样编写它:

If (var !== null || var !== undefined || var !== false) {
 return  var !== var2
}

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

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