我不明白为什么 CC 没有进一步编码高尔夫。我经常使用“guard”语句编写,例如 var x = obj.fun && obj.fun();
。但 CC 不会将 if
简化为“guard”。
编译后的js和预期的js真的不一样吗?
未编译的源代码:
window.test = function () {
var ret = false;
if (Math.random) {
ret = Math.random() < 0.5;
}
return ret;
}
命令
npx google-closure-compiler \
--compilation_level ADVANCED \
--js test.js \
--js_output_file out.js
编译输出(美化):
window.test = function() {
var a = !1;
Math.random && (a = 0.5 > Math.random());
return a;
};
预期输出(“我会做什么”):
window.test = function () {
return Math.random && 0.5 > Math.random();
}
最佳答案
如果 Math.random 函数不存在,此代码将返回 undefined
:
return Math.random && 0.5 > Math.random();
我认为返回 false
和返回 undefined
之间可能存在差异。
关于javascript - 闭包编译器没有使用 && 将此 if 语句扁平化为 "guard",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50205803/