gpt4 book ai didi

javascript - 为什么 JavaScript 解构不能内联工作

转载 作者:行者123 更新时间:2023-12-01 02:06:06 25 4
gpt4 key购买 nike

在哈希颜色函数中,我通过从另一个对象解构它们来分配标题和评级,而是分配全颜色对象,如果我将代码分成两行(首先解构并分配(重建),那么它可以正常工作。请解释一下这背后的逻辑。

const colors = [{
id: '-xekare',
title: "rad red",
rating: 3
}, {
id: '-jbwsof',
title: "big blue",
rating: 2
}, {
id: '-prigbj',
title: "grizzly grey",
rating: 5
}, {
id: '-ryhbhsl',
title: "banana",
rating: 1
}]

hashcolor=colors.reduce((hash,color)=>{
hash[color.id]={title,rating}=color
return hash
},[])

console.log(hashcolor);

最佳答案

当您解构时,您正在创建(或分配给)单个变量 - 您不是在创建新对象,因此 hash[color.id] = { title ,评级}实际上不起作用。您可以编写(或复制)一个 pick 函数来完成此任务,但在这种情况下,您可以只在参数中进行解构。

您可能还应该使用对象作为累加器,而不是数组:

const colors = [{
id: '-xekare',
title: "rad red",
rating: 3
}, {
id: '-jbwsof',
title: "big blue",
rating: 2
}, {
id: '-prigbj',
title: "grizzly grey",
rating: 5
}, {
id: '-ryhbhsl',
title: "banana",
rating: 1
}]

const hashcolor = colors.reduce((hash, { id, title, rating }) => {
hash[id] = { title, rating };
return hash;
}, {})

console.log(hashcolor);

关于javascript - 为什么 JavaScript 解构不能内联工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50094635/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com