在 Perl 中我可以说:
@a = ();
unshift @a; # @a is still ()
unshift @a, (); # @a is still ()
unshift @a, 1>0 ? 1 : 0; # @a is now (1)
unshift @a, 1>0 ? () : 0; # @a is still (1)
如果存在的话,JavaScript 等效语法是什么?
a=[];
a.unshift(); # a is still []
a.unshift(...[]); # a is still []
a.unshift( 1>0 ? 1 : 0); # a is now [1]
a.unshift( 1>0 ? ...[] : 0 ); # syntax error
a.unshift( 1>0 ? (...[]) : 0 ); # syntax error
a.unshift( 1>0 ? [] : 0 ); # a is now [[],1]
您不能在已有扩展语法的情况下将其用作条件(三元)运算符的操作数。相反,请反转扩展语法和条件运算符的顺序,并确保条件运算符始终求值为可迭代对象 -- 因此请提供以下内容,
[0]
而不是0
:正如 Mozilla 贡献者所写:
条件运算符的操作数并不是这样一种位置,因为在
?
和:
符号之间只需要一个操作数。