Why does having [].map with curly brackets change the way it works?

后端 未结 4 1084
轮回少年
轮回少年 2021-01-23 02:15

So, basically I have this:

Array.prototype.toString = function() {
    return (\"[\" + this.map(thing => thing = \'\"\' + thing + \'\"\').join(\', \') + \"]\"         


        
4条回答
  •  时光取名叫无心
    2021-01-23 02:49

    This has nothing to do with arrays or the map method. It is entirely about how arrow functions work.

    When you give a single statement on the right hand side, then that statement is evaluated and returned inside the function.

    foo => bar
    

    is equivalent to:

    function (foo) { return bar; }
    

    When you put a block on the right hand side, that block simply because the function body.

    foo => { bar }
    

    is equivalent to:

    function (foo) { bar; }
    

    In this second version, you have no return statement, so the function returns undefined.

    You need to make the return statement explicit if you use a block.

    foo => { return bar; }
    

提交回复
热议问题