首页 > 解决方案 > What is the point of having multiple values after a return statement?

问题描述

I was messing around with an AST tree parser and I saw that a ReturnStatement can have multiple expressions. As you can see in the following snippet there are multiple values after the return statement and yet the code get compiled and run successfully (its the last value that gets returned).

function test() {
  return 1, 2, 3;
}

console.log(test());

AST Form:

{
    "type": "ReturnStatement",
    "start": 13,
    "end": 24,
    "argument": {
        "type": "SequenceExpression",
        "start": 20,
        "end": 23,
        "expressions": [{
            "type": "Literal",
            "start": 27,
            "end": 28,
            "value": 1,
            "raw": "1"
        }, {
            "type": "Literal",
            "start": 30,
            "end": 31,
            "value": 2,
            "raw": "2"
        }, {
            "type": "Literal",
            "start": 33,
            "end": 34,
            "value": 2,
            "raw": "3"
        }]
    }
}

What is the point of this feature and/or bug?
When would you ever want to use this syntax?

标签: javascriptreturn

解决方案


1, 2, 3不是多个表达式,它是带有逗号运算符的单个表达式,SequenceExpression在您的 AST 中调用。逗号仅在子表达式有副作用时才有意义。例如,有些人喜欢这样写reduce回调:

let count = ary => ary.reduce(function (o, x) { 
    return o[x] = ++o[x] || 1, o 
}, {})

在这里,逗号用于执行副作用o[x] = ...,然后返回累加器。

逗号运算符主要是为了简洁,没有它你总是可以相处的:

let count = ary => ary.reduce(function (o, x) { 
    o[x] = ++o[x] || 1; 
    return o 
}, {})

推荐阅读