Vel*_*dan 1 javascript lambda expression arrow-functions
我只是想知道为什么当我试图返回一个对象时,我立即为它分配一些值,结果不是我预期的,而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?
Run Code Online (Sandbox Code Playgroud)
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!
Run Code Online (Sandbox Code Playgroud)
请有人帮助我,了解这一刻吗?我相信这是一个有点愚蠢的问题,但无论如何,我会非常感谢任何信息.谢谢!
分配,例如res[key] = 0返回指定的值 - 0.您需要返回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)Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
121 次 |
| 最近记录: |