如何将一个数组乘以一个百分比

How to multiply an array by a percentage?

本文关键字:一个 百分比 数组      更新时间:2023-09-26

我有一些困难完成我的代码。它工作得很好,除了我不知道如何用百分比乘以我的数字数组。下面是我的代码:

<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>

感谢所有的帮助!

当你问如何乘(我假设你想要7%)答案将是

var numbers = [12.3, 20, 30.33];
numbers = numbers.map(function(i){
  return Math.round(i*.07 * 100)/100;
});
console.log(numbers);

与数组相乘总是得到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>