[英]How to make an argument function which subtracts numbers
I want the first number to be positive, like 10-20-30, not -10-20-30我希望第一个数字是正数,比如 10-20-30,而不是 -10-20-30
function substractAll() { var sum = 0 for (var i = 0; i < arguments.length; i++) { sum -= arguments[i] } console.log(sum) } substractAll(10, 20, 30)
You can extract the first argument first in the parameter list:您可以首先提取参数列表中的第一个参数:
function substractAll(initial, ...rest) { var sum = initial; for (var i = 0; i < rest.length; i++) { sum -= rest[i]; } console.log(sum) } substractAll(10, 20, 30)
Or use .reduce
, and depend on the initial value for the .reduce
callback being the first accumulator, the only positive value, thanks @JaromandaX:或者使用.reduce
,并依赖于.reduce
回调的初始值是第一个累加器,唯一的正值,谢谢@JaromandaX:
function substractAll(...args) { const sum = args.reduce((a, b) => a - b); console.log(sum) } substractAll(10, 20, 30)
Start by setting sum
to the first number instead of 0
, then loop over the remaining numbers.首先将sum
设置为第一个数字而不是0
,然后遍历剩余的数字。
function substractAll() { var sum = arguments[0]; for (var i = 1; i < arguments.length; i++) { sum -= arguments[i] } console.log(sum) } substractAll(10, 20, 30)
You can assign the first argument to sum as positive and then iterate the other arguments starting the for loop at index = 1:您可以将 sum 的第一个参数指定为正数,然后迭代其他参数,从 index = 1 处开始 for 循环:
function substractAll(){ var sum = 0; sum = arguments[0]; for(let i = 1; i < arguments.length; i++){ sum -= arguments[i] } console.log(sum) } substractAll (10, 20, 30)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.