简体   繁体   中英

Adding numbers to array elements

I want to add some number to elements of any array but I get NaN. I know why we have all NaN. Just want to know a way to do something similar.

 var a = []; for(var i=0;i<6;i++){ for(var j=0;j<2;j++){ var random_number = Math.floor(Math.random() * 10) + 1; a[i] += random_number } } console.log(a) //[NaN, NaN, NaN, NaN, NaN, NaN] 

+= ... is appending ... to whatever was previously in your variable. Here, it's appending a number to an unset value, giving NaN .

Just get rid of your += when setting your array values :

 var a = []; for(var i=0;i<6;i++){ for(var j=0;j<2;j++){ var random_number = Math.floor(Math.random() * 10) + 1; a[i] = random_number; } } console.log(a) 

You could take a default value of zero instead of undefined for addition.

 var a = [], i, j, random_number; for (i = 0; i < 6; i++) { for (j = 0; j < 2; j++) { random_number = Math.floor(Math.random() * 10) + 1; a[i] = (a[i] || 0) + random_number; } } console.log(a) 

Just remove '+=' , instead just use '='

You are assigning a number to an unassigned variable. That's why you are getting NaN error.

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