javascript - 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?
解决方案
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
}, {})
推荐阅读
- c# - 通过 ajax 发布的 Asp.net core 2.0 错误更新模型
- sql - 了解 SQL Select 语句结果中的未命名列
- ms-access - 使用 MS-Access 2010 中的多选和列计数属性在 listbox2 中显示来自 listbox1 的内容
- javascript - jQuery 更改为隐藏字段后,在 Gravity Forms 中触发表单更新
- video.js - 如何使用巨大的插件在 video.js 播放器中隐藏广告的搜索栏
- google-chrome - 在 Vue 开发工具 (vue2/vuex3) 中未检测到 Vuex 存储
- dropdown - 为同一个下拉列表实现多个链接
- ios - WKWebView 无法设置 Cookie (iOS 11+)
- python - SQLAlchemy 未检测到 _determine_joins 上的 ForeignKeys,NoForeignKeysError
- javascript - 未弹出/更新配置的意外令牌导入