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

后端 未结 4 1079
轮回少年
轮回少年 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:53

    Because when you add {}, it turns it from a pure functional-style arrow function into a normal function, just it has arrow syntax. If you want to return a value from this, you need to explicitly write return thing; at the end:

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

    The reason the pure arrow function works is because the statement thing = '"' + thing + '"' actually returns the result, and hence is the return value of the function. You could get exactly the same result without reassigning thing:

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

提交回复
热议问题