js处理分数相加
作者:互联网
const list = ['1/3', '1/4', '1/5', '1/6'];
console.log(CalculateFraction(list));
function CalculateFraction (list) {
if (list.length === 0) {
return false
}
let denominator = 0 //分母
let denominators = [] //分母集合
let numerator = 0 // 分子
let numerators = [] //分子集合
list.forEach(item => {
const [n, d] = item.split('/')
numerators.push(n)
denominators.push(d)
})
// 根据分母找出最小公倍数
let pre = parseInt(denominators[0])
let leastMultiple = pre
for (let i = 1; i < denominators.length; i++) {
const d = denominators[i]
leastMultiple = d > pre ? d : pre
while (leastMultiple <= pre * d) {
if (leastMultiple % d === 0 && leastMultiple % pre === 0) {
break
}
leastMultiple++
}
pre = leastMultiple
}
denominator = leastMultiple
numerators.forEach((item, index) => {
numerator += item * (denominator / denominators[index])
})
return numerator + '/' + denominator
}
标签:分数,pre,const,相加,list,js,leastMultiple,let,denominators 来源: https://www.cnblogs.com/samsara-yx/p/16200232.html