javascript函数返回的语法(空格)会影响结果吗? [英] Does the syntax (whitespace) of a javascript function return affect the result?
问题描述
在编写一个JavaScript函数来评估多变量条件时,我发现在Javascript中看起来像是一个解析器错误。请让我知道如果我忘记了某些东西,或者这是适当的行为。
In writing a javascript function to evaluate a multi-variate condition, I came across what seems like a parser error in Javascript. Please let me know if I'm forgetting something, or if this is appropriate behavior.
在我的函数中,我返回 AND
几个变量的结果,如下所示:
In my function, I'm returning the AND
result of several variables, like so:
return
// a comment, for kicks
a1 && a2
&&
b1 && b2
&&
// another comment
c1 && c2
&&
d1 && d2
;
然而,即使所有这些变量都有一个显式值 true
,该函数返回 undefined
而不是预期的 true
。
However, even when all of those variables have an explicit value of true
, the function is returning undefined
instead of the expected true
.
我已经尝试了几个返回此表达式的变体,我发现:
I've tried several variations of returning this expression, and I've found:
- 多行表达式 - 失败
- 单行上的表达式 -
- 在paretheses中包装表达式 - 工作
- 将多行表达式设置为变量,然后返回变量 -
- multiline expression -- fails
- expression on single line -- works
- wrapping expression in paretheses -- works
- setting multiline expression to variable, then returning variable -- works
查看工作示例: http://jsfiddle.net/drzaus/38DgX/
有人可以解释为什么会这样吗?
Can anybody explain why this happens?
推荐答案
这是正确的行为。在函数中放置 return;
将导致它返回 undefined
。在你的例子中, return
之后的换行符使得解析器认为这是语句的结尾,所以它返回 undefined
。
This is correct behavior. Putting return;
in a function will cause it to return undefined
. In your example, the line break after return
makes the parser think this is the end of the statement, so it returns undefined
.
这篇关于javascript函数返回的语法(空格)会影响结果吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!