0

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

asked Sep 11, 2012 at 22:13
3
  • 1
    There is no automatic cast from array to 2 numbers. Commented Sep 11, 2012 at 22:16
  • 2
    @KaiMattern: multiply.apply(null, numbers); Commented Sep 11, 2012 at 22:18
  • Holy crap, that is cool. Thanks @grey Commented Sep 12, 2012 at 6:18

4 Answers 4

6

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.

answered Sep 11, 2012 at 22:17
Sign up to request clarification or add additional context in comments.

Comments

5

You're only passing one argument to multiply. Inside the function num1 is an array and num2 is undefined.

What you want to do is this,

var result = multiply(numbers[0], numbers[1]);
gen_Eric
228k42 gold badges304 silver badges343 bronze badges
answered Sep 11, 2012 at 22:14

Comments

1

you are passing an array into multiply where multiply expects 2 numbers.

when you try to multiply an array it makes sense that the result is NaN which stands for Not a number.

try:

var results = multiply(numbers[0], numbers[1]);
answered Sep 11, 2012 at 22:16

Comments

0

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.

answered Sep 11, 2012 at 22:18

1 Comment

this doesn't really answer the problem. The issue is with the method of calling the function multiply not that the OP isn't defining the array as you mention.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.