我在完成代码时遇到了一些困难。它工作得很好,除了我无法弄清楚如何将我的数组乘以一个百分比。这是我的代码:
<p>Click the button to get the sum of the numbers in the array.</p>
<button onclick="myFunction()">Try it</button>
<p>Sum of numbers in array: <span id="demo"></span></p>
<p>Amount with 7% tax added: <span id="percent"></span></p>
<script>
var numbers = [12.3, 20, 30.33];
function getSum(total, num) {
return total + num;
}
function myFunction(item) {
document.getElementById("demo").innerHTML = numbers.reduce(getSum);
}
function myFunction(item) {
document.getElementById("percent").innerHTML = (numbers * .07);
}
</script>
感谢所有帮助!
答案 0 :(得分:1)
当你问如何繁殖时(我假设你想要7%)答案就是
var numbers = [12.3, 20, 30.33];
numbers = numbers.map(function(i){
return Math.round(i*.07 * 100)/100;
});
console.log(numbers);
答案 1 :(得分:1)
与数组相乘总是得NaN
。我想你需要得到总和的7%
然后得到总和,然后通过乘以计算百分比。
numbers.reduce(getSum) * .07
<p>Click the button to get the sum of the numbers in the array.</p>
<button onclick="myFunction()">Try it</button>
<p>Sum of numbers in array: <span id="demo"></span>
</p>
<p>Amount with 7% tax added: <span id="percent"></span>
</p>
<script>
var numbers = [12.3, 20, 30.33];
function getSum(total, num) {
return total + num;
}
function myFunction(item) {
document.getElementById("demo").innerHTML = numbers.reduce(getSum);
}
function myFunction(item) {
document.getElementById("percent").innerHTML = numbers.reduce(getSum) * .07;
}
</script>