在物理学中,串联连接的3个电阻的等效电阻为-
R = R1 + R2 + R3
并联电阻的等效电阻为-
R = (1/R1) + (1/R2) + (1/R3)
我们需要编写一个JavaScript函数,该函数接受一个字符串,该字符串具有两个可能的值:“串联”或“并行”,然后是代表n个电阻器电阻的n个数字。
函数应返回这些电阻的等效电阻。
让我们为该函数编写代码。
const r1 = 5, r2 = 7, r3 = 9;
const equivalentResistance = (combination = 'parallel', ...resistors) => {
if(combination === 'parallel'){
return resistors.reduce((acc, val) => (1/acc) + (1/val));
};
return resistors.reduce((acc, val) => acc + val);
};
console.log(equivalentResistance('parallel', r1, r2, r3));输出结果
以下是控制台中的输出-
3.0277777777777777