19

The last few days, I've been helping a friend learn Javascript. It's his first language in years and he remembers virtually nothing, so he's been starting pretty much entirely from scratch. He's been going through a simple tutorial and I've been providing him with some exercises to help him practice. The most recent exercise I gave him was the (apparently) classic FizzBuzz problem. He solved it with a bit of help, but he did something very interesting while working out his solution. He came up with the following code:

for (var x = 1; x <= 100; x++) {
    if (x%3 == 0, x%5 != 0) {
        console.log("Fizz");
    }
    else if (x%3 != 0, x%5 == 0) {
        console.log("Buzz");
    }
    else if (x%3 == 0, x%5 == 0) {
        console.log("FizzBuzz");
    }
    else {
        console.log(x);
    }
}

He wasn't familiar with boolean comparison operators, so he didn't use && and instead used commas. My expectation was that it would crash and say something about a syntax error, but to my surprise it ended up running fine and just printing out a bunch of "Fizz" and "Buzz" lines, with no "FizzBuzz" or numbers. Needless to say, I was confused, so I did a bit of experimentation. My first test was to run this:

if (true, true) console.log('true, true');
if (true, false) console.log('true, false');
if (false, true) console.log('false, true');
if (false, false) console.log('false, false');

Which gave me two lines of output:

'true, true'
'false, true'

From that, I made the guess that all comma did was cause it to evaluate nothing but the last expression in the list. I then tried running this code:

for (var i = 0; i < 16; i++) {
    if ((Math.floor(i / 8) == 1), (Math.floor(i / 4) == 1), (Math.floor(i / 2) == 1), (i % 2 == 1)) {
        console.log(i);
    }
}

The output I got was all the odd numbers from 1-15, which confirmed my guess from my first test (since the last boolean in the comma-separated list was flipping every other iteration).

After all that long-winded context, my question is this: Is this comma syntax a known and intentional piece of the Javascript engine, or is it a strange, overlooked quirk of the interpreter? I know commas can be used for a few other things (initializing multiple variables in one line, declaring arrays, and separating parameters jump to mind), but I've never heard of them being used in conditional statements like this in any language, and I'm curious if anyone else knows whether or not this code should even run.

For reference, the FizzBuzz code and the second test I ran were both done using node, and the first test I ran was done in the Javascript console in Chrome, so it doesn't seem to be just a browser- or node-exclusive quirk if indeed it is one. Also, if you actually read this far, thank you.

4

1 回答 1

27

逗号是一个实际的运算符。它计算它的两个操作数(从左到右)并返回第二个操作数的值。

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comma_Operator

它最常见的用法是在for循环中提供多个参数,但它也可以用于其他目的。

于 2013-09-05T03:54:21.000 回答