- 1

How to calculate the number in an array by using function?

for example, an array include {14,23,5,30} how to use a function to show 30-23=7? I tried this but it is not correct: function calculate(array1, array2){ var newArray []; newArray[0]=difference(newArray[3],newArray[2]); }

24th Jan 2018, 4:27 AM
Cory Li
Cory Li - avatar
2 Answers
+ 3
array = [15,23,5,30]; function subtract(){ var x = array[3]; var y = array[1]; var ans = x - y; console.log(ans) }; subtract() Is this what you want.....
24th Jan 2018, 5:24 AM
Rohit
Rohit - avatar
+ 1
If you want to display "30-23=7", then you need to return a string... function calculate(array1) { var calculation; calculation = array1[3] - array1[1]; return array1[3].toString() + '-' + array1[1].toString() + '=' + calculation; }
24th Jan 2018, 5:32 AM
William Coronado
William Coronado - avatar