What does a comma do in JavaScript expressions?

前端 未结 5 1554
礼貌的吻别
礼貌的吻别 2020-11-21 05:22

If I use:

1.09 * 1; // returns \"1.09\"

But if I use:

1,09 * 1; // returns \"9\"

I know that 1,09 isn\'t

5条回答
  •  爱一瞬间的悲伤
    2020-11-21 06:00

    Adding/modifying properties to an object and returning it in the same line is a possible use-case:

    console.log(
      ((x) => (o = {biggerCond: r => r >= x},
               o.r5 = Array.from(window.crypto.getRandomValues(new Uint16Array(5))),
               o.isAnyBigger = o.r5.some(o.biggerCond),
               o.bigger = o.isAnyBigger ? o.r5.filter(o.biggerCond) : [x], o )
      )(5e4)
    );
    // Example
    // {
    //   bigger: [58414, 56500, 63397],
    //   isAnyBigger: true,
    //   isBiggerCond: r => r >= x,
    //   r5: [58414, 12015, 56500, 63397, 43861]
    // }

    The above anonymous function returns an object with random values bigger than the input value or, if there's none, with the input value itself in an array in contained in the bigger property.

    It is still syntactic sugar (like arrow functions), but it does shorten the number of lines... I wonder if some JS minifiers detect and adjust the code in a similar way automatically. Run it in your console:

    ((x)=>(o={biggerCond:r=>r>=x},o.r5=Array.from(window.crypto.getRandomValues(new Uint16Array(5))),o.isAnyBigger=o.r5.some(o.biggerCond),o.bigger=o.isAnyBigger?o.r5.filter(o.biggerCond):[x],o))(5e4)
    

提交回复
热议问题