if (browser == ‘chrome’||’firefox’||’safari’||’opera’)
有人可以解释一下为什么 if 条件对于浏览器的所有值都计算为 true 吗?
最佳答案
首先删除大引号 - 那些会导致语法错误。请改用直引号。
==
的运算符优先级高于 ||
,并且 ||
从左到右计算,因此修复引号,您的代码相当于:
if ((((browser == 'chrome') ||'firefox') ||'safari') ||'opera')
如果浏览器是 Chrome,则结果为
if ((((true) ||'firefox') ||'safari') ||'opera')
if (true)
否则,这会导致
if ((((false) || 'firefox') ||'safari') ||'opera')
if (((false || 'firefox') ||'safari') ||'opera')
如果||
的左侧为假,则其计算结果为右侧的值。否则,如果 ||
的左侧为真,它将计算左侧的值。所以它决定:
if (((false || 'firefox') ||'safari') ||'opera')
if ((('firefox') ||'safari') ||'opera')
if ('firefox')
并且 'firefox'
是 true,因此 if
将始终运行。
对于您想要执行的操作,请使用 .includes
代替:
if (['chrome', 'firefox', 'safari', 'opera'].includes(browser))
关于javascript - JavaScript 中的运算符优先级 : Can someone please explain why the if condition evaluates to true for all values of browser,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60841996/