【问题标题】:Javascript lambda(arrow) function returns object in a moment of a value assigningJavascript lambda(arrow) 函数在赋值的瞬间返回对象
【发布时间】:2018-04-06 15:25:23
【问题描述】:

我只是想知道为什么当我试图返回一个对象时,当我立即为其分配一些值时,结果与我预期的不同,并且 lamda 函数没有返回一个对象而是返回值。

为了澄清我的问题,这里是代码:

1) 错误的变体(但我想使用类似的东西,因为它有点短)

const a = {
 "a" : "a",
 "b" : "b",
 "c" : "c"
}

const res = Object.keys(a).reduce((res, key) => ( res[key] = 0 ), {});
console.log(res) // result -> 0; but why, does it return an assigning value in that case?

2 个变体(正确但有点长)

const a = {
 "a" : "a",
 "b" : "b",
 "c" : "c"
}

const res = Object.keys(a).reduce((res, key) => { res[key] = 0; return res; }, {});
console.log(res); // { "a" : 0, "b" : 0, "c" : 0 }. It works properly now!

有人可以帮我理解这一刻吗?我相信这是一个有点愚蠢的问题,但无论如何我都会非常感谢您提供任何信息。谢谢!

【问题讨论】:

标签: javascript lambda expression arrow-functions


【解决方案1】:

赋值,如res[key] = 0返回赋值-0,需要返回res。您可以使用comma operator 返回最后一个值(res):

const a = {
 "a" : "a",
 "b" : "b",
 "c" : "c"
}

const res = Object.keys(a).reduce((res, key) => (res[key] = 0, res), {});
console.log(res)

【讨论】:

    猜你喜欢
    • 2019-02-14
    • 2011-04-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-26
    • 1970-01-01
    • 2014-10-12
    • 2020-04-23
    相关资源
    最近更新 更多