Hi all just wondering why the following code results in NaN?
function multiply(num1,num2){
var total = num1 * num2;
return total;
}
var numbers = Array(10,2);
var results = multiply(numbers);
alert (results);
Thanks
Use .apply to invoke the function.
var results = multiply.apply(null, numbers);
The .apply method invokes the multiply function, but accepts an Array or Array-like collection as the second argument, and sends the members of the collection as individual arguments.
FYI, the first argument to .apply sets the calling context. I passed null since your function makes no use of this.
This technique is especially useful if you decide to have your multiply function take a variable number of arguments. Using .apply, it won't matter how many are in the Array. They will be passed as individuals.
When calling array values, you must define the value in the array.
For example:
var numbers = Array(10, 2)
JavaScript starts the array count at 0, so numbers[0] would be equal to 10 and numbers[1] would be equal to 2.
multiply.apply(null, numbers);