Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/366.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 括号是否阻止分号插入?_Javascript_Line Breaks_Automatic Semicolon Insertion - Fatal编程技术网

Javascript 括号是否阻止分号插入?

Javascript 括号是否阻止分号插入?,javascript,line-breaks,automatic-semicolon-insertion,Javascript,Line Breaks,Automatic Semicolon Insertion,假设我想将一组变量设置为null(并且不想使用数组/循环结构),或者我只想跨多行编写一个大型布尔表达式。在这种情况下,未闭合的括号是否会阻止分号插入?例如 some_variable = another_variable = yet_another_variable = ( oh_look_a_parenthesis_above_me = hey_heres_another_variable) = ( and_for_some_reason_another = last_one)

假设我想将一组变量设置为null(并且不想使用数组/循环结构),或者我只想跨多行编写一个大型布尔表达式。在这种情况下,未闭合的括号是否会阻止分号插入?例如

some_variable = another_variable = yet_another_variable = (
    oh_look_a_parenthesis_above_me = hey_heres_another_variable) = (
    and_for_some_reason_another = last_one) = null;

与使用
&
|
=
在换行符上对表达式进行分组相比,这两种方法的效果如何?也就是说,这也会一直有效吗

some_variable = another_variable = 
    a_variable_after_a_line_break = and_one_more;

while(test_for_an_expr && another_test || 
    (an_expr_here && and_an_expr_here)) {
    // ...
}

我正在寻找一种在所有浏览器(包括IE6+)中都是最标准的方式。

只有当您有代码时才会插入分号,如果没有分号,这将是一个语法错误。在您的例子中,表达式是完全有效的,所以您不需要担心分号插入括号与否

将插入分号的示例:

var a = 1
var b = 2
在上述情况下,在换行符处插入分号,但这只是因为写入以下内容是一个语法错误:

var a = 1 var b = 2
var a = 1; var b = 2
但写下以下内容是完全正确的:

var a = 1 var b = 2
var a = 1; var b = 2
这些规则变得很棘手,因为JavaScript语法中存在一些不允许换行的实例。例如,“
return
”关键字和要返回的值之间不允许换行。这是一个语法错误:

return
  17;
但分号插入“修复”此错误的方法是插入如下分号:

return;
  17;
这可能不是作者的本意! 在这种情况下,可以使用括号来防止分号插入:

return (
   17);
因为只有在return关键字和表达式开头之间才允许换行。在表达式内部,这不是问题

在这种情况下,未闭合的括号是否会阻止分号插入

对。虽然没有必要:

与使用
&
|
=
在换行符上对表达式进行分组相比,这两种方法的效果如何

完全一样。它们是需要第二部分的表达式,因此ASI不能-不得-在不使结果无效的情况下启动


ASI仅在连续行不带分号无效时发生。有关详细信息,请参阅。

AFAIK,JavaScript不关心空格(让您的担忧变得毫无意义)。@Brad:JavaScript在某些情况下确实关心换行。@JacquesB:只引用字符串和一些逻辑情况,但我指的更多的是延长条件表达式。这非常有见地。谢谢