为什么 /* */ 注释的行为不同? Javascript 错误?
Why does /* */ comment behave differently ? Javascript bug?
这真的很奇怪。为什么 fx2 returning 'undefined' 而 fx1、fx2 和 fx3 正确 return 'true' ?
<script>
function fx1(item) {
return (item.a == 1)
&& (item.b == 1);
}
function fx2(item) {
return /*(item.a == 1)
&& */(item.b == 1);
}
function fx3(item) {
return true//(item.a= 1)
&& (item.b == 1);
}
function fx4(item) {
return (item.b == 1);
}
alert(fx1({a: 1, b: 1}));
alert(fx2({a: 1, b: 1}));
alert(fx3({a: 1, b: 1}));
alert(fx4({a: 1, b: 1}));
</script>
在 http://www.codetuning.net/temp/commentedwherejsbug.html
上在线试用
这当然是我原始代码的简化版本,仅重现这个问题。最初我有 fx1,然后我认为可能不需要第一个条件(测试 item.a),所以我将其注释掉,就像在 fx2 中一样。为什么这不起作用? fx3 和 fx4 按预期工作,它们都 return 正确,除了 fx2 return 未定义。
已在 IE11 和 Chrome 47 上测试。
有人能说服我这不是 Javascript 中的错误吗?
function fx2(item) {
return /*(item.a == 1)
&& */(item.b == 1);
}
javascript 会自动在 return
之后放置一个 ;
。将所有 return 语句放在同一行。喜欢
return (item.a == 1) && (item.b == 1);
这真的很奇怪。为什么 fx2 returning 'undefined' 而 fx1、fx2 和 fx3 正确 return 'true' ?
<script>
function fx1(item) {
return (item.a == 1)
&& (item.b == 1);
}
function fx2(item) {
return /*(item.a == 1)
&& */(item.b == 1);
}
function fx3(item) {
return true//(item.a= 1)
&& (item.b == 1);
}
function fx4(item) {
return (item.b == 1);
}
alert(fx1({a: 1, b: 1}));
alert(fx2({a: 1, b: 1}));
alert(fx3({a: 1, b: 1}));
alert(fx4({a: 1, b: 1}));
</script>
在 http://www.codetuning.net/temp/commentedwherejsbug.html
上在线试用这当然是我原始代码的简化版本,仅重现这个问题。最初我有 fx1,然后我认为可能不需要第一个条件(测试 item.a),所以我将其注释掉,就像在 fx2 中一样。为什么这不起作用? fx3 和 fx4 按预期工作,它们都 return 正确,除了 fx2 return 未定义。
已在 IE11 和 Chrome 47 上测试。
有人能说服我这不是 Javascript 中的错误吗?
function fx2(item) {
return /*(item.a == 1)
&& */(item.b == 1);
}
javascript 会自动在 return
之后放置一个 ;
。将所有 return 语句放在同一行。喜欢
return (item.a == 1) && (item.b == 1);