Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/html/81.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何将数组乘以百分比?_Javascript_Html_Arrays - Fatal编程技术网

Javascript 如何将数组乘以百分比?

Javascript 如何将数组乘以百分比?,javascript,html,arrays,Javascript,Html,Arrays,我在完成代码时遇到了一些困难。它工作得很好,只是我不知道如何将我的数字数组乘以一个百分比。这是我的密码: <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">&

我在完成代码时遇到了一些困难。它工作得很好,只是我不知道如何将我的数字数组乘以一个百分比。这是我的密码:

<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%增值税的金额:

风险值=[12.3,20,30.33]; 函数getSum(总计,num){ 返回total+num; } 功能myFunction(项目){ document.getElementById(“demo”).innerHTML=numbers.reduce(getSum); } 功能myFunction(项目){ document.getElementById(“百分比”).innerHTML=(number*.07); }

感谢您的帮助

当你问如何乘法时(我想你想要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
单击按钮以获取数组中的数字之和

试试看 数组中的数字之和:

含7%增值税的金额:

风险值=[12.3,20,30.33]; 函数getSum(总计,num){ 返回total+num; } 功能myFunction(项目){ document.getElementById(“demo”).innerHTML=numbers.reduce(getSum); } 功能myFunction(项目){ document.getElementById(“百分比”).innerHTML=numbers.reduce(getSum)*.07; }
您需要先求和,然后计算百分比
数字。如上所述,减少(getSum)*.07
您需要先对元素求和,然后相乘(如果不大于,则不相乘,这对任何人来说都很奇怪,包括JS)。您可能还希望创建另一个数组,使用array.prototype.forEach()方法将所有项目乘以税率。顺便说一句,不管编码问题。将其乘以0.07将得到税额,而不是加了税的金额。你想把它乘以1.07。