第一种 一边循环数据源一边计算乘积
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<button onclick="commit()">确定</button>
</body>
<script>
function commit() {
var fenzi = 2
var fenmu = 1
var n = 3
// 2/1 3/2 5/3
var newsumzi = 2
var newsumfenmu = 1
for (var i = 1; i < 5; i++) {
var nextzi = fenzi + fenmu
var nextmu = fenzi
var tempzi = 1
var tempmu = 1
tempzi = newsumzi * nextmu + newsumfenmu * nextzi
newsumzi = tempzi
tempmu = newsumfenmu * nextmu
newsumfenmu = tempmu
fenzi = nextzi
fenmu = nextmu
}
console.log(tempmu)
console.log(tempzi)
var yinshu = 1
yinshu = gongyueshu(tempzi,tempmu); // 求最大因数
console.log('最大公因数' + yinshu)
if (yinshu !== 1) {
console.log(tempzi/yinshu + '/' + tempmu/yinshu)
}else{
console.log(tempzi + '/' + tempmu)
}
}
function gongyueshu(num1, num2) {
var a = num1
var b = num2
var c = a * b
if (a < b) {
var temp = a
a = b
b = temp
}
while (b !== 0) {
var temp = a % b
a = b
b = temp
}
return a
}
</script>
</html>
第二种,先循环数据源,然后求出分母之积
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title></title> </head> <body> <button οnclick="commit()">确定</button> </body> <script> function commit() { var x = 1 var data = [{a: 2, b: 1}] for (var i = 1; i < 3; i++) { var temp = data[i - 1] data.push({a:temp.a + temp.b, b: temp.a}) x *= b } console.log(data) console.log(x) var sum = 0 for (var item of data) { sum += item.a * x / item.b } console.log(sum) </script> </html>