简体   繁体   中英

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

 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:

 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.

 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:

 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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM