javascript - 了解JavaScript逗号运算符

标签 javascript operators comma

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/

相关文章:

javascript - 更改按钮 onclick 函数时设置参数?

javascript - 这个 javascript ajax 代码有什么问题?

C++ 运算符 = 问题

perl - 是否有类似引号的内插单词列表运算符?

java - 对象相等(对象引用 "==")

javascript - 使用 jQuery 进行拖放

javascript - TypeError : this. props.* 不是函数

python - 如何一次从 Pandas 的所有列中删除逗号

sql - 用逗号将一个字符串拆分为多列

python - Python:对象名称中的尾部逗号