简体   繁体   中英

How to get total sum of array

i'm trying to add together the contents of an array (integers). for example:

var myArray;
var answer;
myArray[0]=2;
myArray[1]=5;
answer=myArray[0]+myArray[1];

answer should equal 7.Could you help me, please? Thank you so much.

You need to initialize your array

var myArray = [];

As you get more values into your array you might consider a loop, example:

var myArray = [];
var answer = 0;
myArray[0]=2;
myArray[1]=5;

for (var i=0;i<myArray.length;i++)
{ 
   answer += myArray[i];
}

console.log(answer);

Take a look at this: http://www.w3schools.com/js/js_loop_for.asp

When I run your code, I get an error.

you need to intialize your variable myArray to be an array.

var myArray = [];

After I do that, answer has the expected value.

You need to declare myArray as an array, otherwise myArray[0] means a property named 0 on undefined (which will probably blow up) rather than an index access.

var myArray = [];
...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM