最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

JavaScript equivalent of Perl empty list () - Stack Overflow

programmeradmin1浏览0评论

In Perl I can say:

@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)

What, if it exists, is the JavaScript equivalent syntax?

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]

In Perl I can say:

@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)

What, if it exists, is the JavaScript equivalent syntax?

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]
Share Improve this question edited Mar 4 at 13:32 brian d foy 133k31 gold badges213 silver badges605 bronze badges asked Mar 3 at 14:07 jhncjhnc 17.2k2 gold badges14 silver badges32 bronze badges 8
  • 1 You might check on the documentation for unshift(). – mykaf Commented Mar 3 at 14:10
  • What is a.unshift( 1>0 ? (...[]) : 0 ); supposed to do? Do you understand what ... does? – luk2302 Commented Mar 3 at 14:12
  • 1 @luk2302 I want the equivalent of the Perl lines I showed. In particular, the fourth line – jhnc Commented Mar 3 at 14:13
  • 2 a.unshift( ...(1>0 ? [] : [0]) ); – luk2302 Commented Mar 3 at 14:16
  • 1 unshift @a, 0 if 1 > 0; and if ( 1 > 0 ) a.unshift( 0 ); are a lot clearer, though. – ikegami Commented Mar 3 at 15:49
 |  Show 3 more comments

1 Answer 1

Reset to default 3

You cannot use the spread syntax where you have it, as an operand of the conditional (ternary) operator. Instead inverse the order of the spread syntax and the conditional operator and make sure the conditional operator always evaluates to an iterable -- so provide [0] instead of 0:

a.unshift(...(1 > 0 ? [] : [0]))

As Mozilla Contributors wrote:

the spread (...) syntax allows an iterable, such as an array or string, to be expanded in places where zero or more arguments (for function calls) or elements (for array literals) are expected.

The operand of the conditional operator is not such a place as exactly one operand is expected between the ? and : symbols.

发布评论

评论列表(0)

  1. 暂无评论