gpt4 book ai didi

javascript - 我怎样才能只使用一次传播?

转载 作者:行者123 更新时间:2023-12-04 00:51:36 25 4
gpt4 key购买 nike

我该如何改进此代码?

const { first, second, three, ...list } = minerals
let newMinerals
if (currentUnit === 'rd') {
newMinerals = {
...list,
first: first * 9.8,
second: second * 9.8,
three: three * 9.8,
}
}
if (currentUnit === 'ch') {
newMinerals = {
...list,
first: first / 9.8,
second: second / 9.8,
three: three / 9.8,
}
}
我有两个块,一个是乘法,第二个是除法,我该如何改进?

最佳答案

我会使用一个根据 currentUnit 改变的回调函数来更改和迭代它以仅转换这些属性,从而创建一个属性数组。和 Object.fromEntries :

const cb = currentUnit === 'rd'
? v => v * 9.8
: currentUnit === 'ch'
? v => v / 9.8
: null;
const props = ['first', 'second', 'third'];
const newMinerals = !cb ? null : {
...minerals,
...Object.fromEntries(
props.map(
prop => [prop, cb(minerals[prop])]
)
)
};
currentUnit总是一个或另一个,它要简单得多:

const currentUnit = 'ch';
const minerals = {
first: 33,
second: 44,
third: 55,
other: 'someother'
};

const cb = currentUnit === 'rd' ? v => v * 9.8 : v => v / 9.8;
const props = ['first', 'second', 'third'];
const newMinerals = {
...minerals,
...Object.fromEntries(
props.map(
prop => [prop, cb(minerals[prop])]
)
)
};
console.log(newMinerals);

关于javascript - 我怎样才能只使用一次传播?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66021710/

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