James
James

Reputation: 1475

javascript numerical array

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

Upvotes: 0

Views: 98

Answers (4)

user1585455
user1585455

Reputation:

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.

Upvotes: 0

gray state is coming
gray state is coming

Reputation: 2107

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.

Upvotes: 6

alanmanderson
alanmanderson

Reputation: 8200

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]);

Upvotes: 1

Aesthete
Aesthete

Reputation: 18848

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]);

Upvotes: 5

Related Questions