简体   繁体   English

Javascript lambda(arrow)函数在赋值时返回对象

[英]Javascript lambda(arrow) function returns object in a moment of a value assigning

I just wonder why when I am trying to return an object when I do immediately assigning some value to it the result is not as I expected and the lamda function doesn't return me an object but the value. 我只是想知道为什么当我立即为它分配一些值时试图返回一个对象时,结果不是我期望的那样,并且lamda函数没有返回一个对象,而是一个值。

To clarify my question here is code: 要在这里澄清我的问题的代码是:

1) Wrong variant ( but I want to use something like that because it's a lil bit shortest) 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 variant (correct but a little bit longest) 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!

Can someone help me, please, to understand this moment? 有人可以帮我理解这一刻吗? I belive that it's a little bit stupid question but anyway I'll be very appreciate for any information. 我相信这是一个愚蠢的问题,但是无论如何我将不胜感激。 Thanks! 谢谢!

Assignments, such as res[key] = 0 return the assigned value - 0. You need to return res . 赋值(例如res[key] = 0返回分配的值res[key] = 0 。您需要返回res You can use the comma operator to return the last value ( res ): 您可以使用逗号运算符返回最后一个值( res ):

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM