不确定在 .map(([key, value]) => [key, value * 2])
中发生了什么,我大致了解参数中方括号的作用。但是有人可以澄清语法规则或者解释一下吗?
以下是我对代码如何工作的理解:
Object.entries
将对象prices
转换为数组,返回类似于[[banana, 1], [orange, 2], [meat, 4]]
的内容。map
是一个数组方法,该函数将每个条目的价格加倍。- 然后将更改重新转换回对象。
如果 map
遍历项目,那么写成 .map((item) => [item[0], item[1] * 2])
是否更合适呢?
正在学习 javascript.info 的课程。
let prices = {
banana: 1,
orange: 2,
meat: 4,
};
let doublePrices = Object.fromEntries(
// convert to array, map, and then fromEntries gives back the object
Object.entries(prices).map(([key, value]) => [key, value * 2])
);
console.log(doublePrices.meat); // 8
.map((item) => [item[0], item[1] * 2])
。 - Ori Drori