Click here to Skip to main content
15,881,852 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello JS Coders,

First I searched the Internet for a solution to adding two array numbers. Nothing made sense.
I am having a hard time understanding how to create an array of numbers that I can do simple math operations on.
var cnum = [4, 5, 2, 7];

If I add cnum[0] and cnum[2] I hope to get 6, but I get 42 ?.

I actually believe I am the worlds worst programmer, and am humble enough to admit it.

JavaScript
   var cnum = [4, 5, 2, 7];
   d = cnum[0] + cnum[2];
   alert("add two array numbers = " d);  // 42 ?

It seems like JS is treating the cnum's as strings.
How can I create arrays that I can preform math on?

Thanks,
Jim
Posted
Comments
[no name] 17-Aug-14 18:45pm    
You would need to use parseInt on the array elements to make them numbers.
JimOr 17-Aug-14 20:46pm    
Wes, OK, I will try the parseInt.

I also put in the missing comma, the Alert text appeared but no result value.

How would I apply parseInt?

Thank You Kindly,
Jim

1 solution

You code is fine except one missing comma in alert.
C#
var cnum = [4, 5, 2, 7];
d = cnum[0] + cnum[2];
alert("add two array numbers = " +d);
 
Share this answer
 
Comments
JimOr 17-Aug-14 21:35pm    
Still having problems with adding two numbers from an array:
Now I have:
var cnum = [4, 5, 2, 7];
alert(parseInt(cnum[1]));
d = parseInt(cnum[0]) + parseInt(cnum[2]);
var cs = d.toString();
alert("add two array numbers = ", cs); //
The above code still does not work. Any ideas?
Peter Leow 17-Aug-14 21:42pm    
Why don't you copy and paste my code to a html page and test it?
JimOr 17-Aug-14 22:51pm    
Thank You Peter.
Kindly,
Jim
JimOr 17-Aug-14 22:27pm    
To: Peter Leow, Yes your suggestion DOES seem to work. (6)

So I continue to explore other suggestions:
Some now working, some not...
var cnum = [4, 5, 2, 7];
alert(parseInt(cnum[3],10) + parseInt(cnum[1],10)); // 12, 7 + 5 = 12, OK this one works
d = (parseInt(cnum[0],10) + parseInt(cnum[2],10)).toString(); // does not work, 4+2 = 6
alert("add two array numbers = ", d); // the two numbers added does not appear.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900