This article by Angus Croll解释JavaScript逗号运算符,如下所示:
//(LHE: left hand expression, RHE right hand expression)
LHE && RHE
1. Always evaluate LHE
2. If LHE is true, evaluate RHE
LHE || RHE
1. Always evaluate LHE
2. If LHE is false, evaluate RHE
LHE, RHE
1. Always evaluate LHE
2. Always evaluate RHE
但是,我使用以下代码进行了jsfiddle测试enter link description here,并且如果运算符为
&&
,则LHE似乎必须用括号括起来。// Works fine
(function one(window) {
window.testOne = function testOne() {
alert("Test one");
}, testOne();
})(window);
// Works, but JSHint complains at *:
// "Expected an assignment or function call but saw instead an expression"
(function two(window) {
(window.testTwo = function testTwo() {
alert("Test two");
}) && testTwo(); // *
})(window);
// Looks good to JSHint, but fails at runtime:
// "ReferenceError: Can't find variable: testThree"
(function three(window) {
window.testThree = function testThree() {
alert("Test three");
} && testThree();
})(window);
您能否解释为什么
testOne
(使用,
)不需要在第一个表达式的圆括号,而testTwo
(使用&&
)却需要括号?为什么JSHint认为test()
不是函数调用?
最佳答案
这是运算符优先级的情况。您使用的运算符具有以下优先级:&&
,||
,=
,,
。
这意味着var ... = ... && ...
等效于var ... = (... && ...)
,但var ... = ... , ....
等效于(var ... = ...) , ....
。
例如,您可以检查优先级here。
关于javascript - 了解JavaScript逗号运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30783680/