我该如何改进此代码?
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,
}
}
我有两个积木,一个是乘法,第二个是除法,我该如何改进?
答案 0 :(得分:3)
我会使用一个根据 Hi im Login Object
和 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
答案 1 :(得分:3)
对我来说最直接的方法是提取条件并注意除以 x
基本上是乘以 1 / x
;
因此,您可以将因子提取到变量 factor
中,该变量取决于单位是 9.8
或 1 / 9.8
,并在任何情况下乘以它。
此外,这是假设只有两种单位选择。对于两个以上,您需要将三元运算符更改为 if-else-if ladder
const { first, second, three, ...list } = minerals;
let newMinerals, factor;
factor = currentUnit === 'rd' ? 9.8 : (1/9.8);
newMinerals = {
...list,
first: first * factor,
second: second * factor,
three: three * factor,
};