我的数组reducer语法有问题。我正在尝试在1和n之间添加所有奇数。我知道我需要额外的格式,但我可以处理。建议?
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Odd counter</title>
<!-- This tool will add odd numbers between 1 and an input number.-->
</head>
<body>
<!-- Input number N-->
<input id="number" type="text"> <button onclick="oddAdder()">
Add odds from 1
</button>
<p id="elements"></p>
</br>
<div id="demo"></div>
<script>
/*
* Check amount.
*/
function oddAdder() {
var sum = [];
var reducer = function(accumulator, item); {
return accumulator + item;
}
var total = sum.reduce(reducer)
var target = document.getElementById("number").value;
for (var i = 1; i <= target; i += 2) {
sum.push(i)
document.getElementById("demo").innerHTML = total;
}
}
/*
* Display total
*/
</script>
</body>
</html>
答案 0 :(得分:0)
在调用sum
之前填充sum.reduce
。另外,从var reducer = function(accumulator, item); {
中删除一个迷路分号。
更正后,获取以下代码。我测试它是否有效。
<html>
<head>
<meta charset="utf-8">
<title>Odd counter</title>
<!-- This tool will add odd numbers between 1 and an input number.-->
</head>
<body>
<!-- Input number N-->
<input id="number" type="text"> <button onclick="oddAdder()">
Add odds from 1
</button>
<p id="elements"></p>
</br>
<div id="demo"></div>
<script>
/*
* Check amount.
*/
function oddAdder() {
var sum = [];
var reducer = function(accumulator, item) {
return accumulator + item;
}
var target = document.getElementById("number").value;
for (var i = 1; i <= target; i += 2) {
sum.push(i)
}
var total = sum.reduce(reducer);
document.getElementById("demo").innerHTML = total;
}
/*
* Display total
*/
</script>
</body>
</html>