0

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]

3 Answers 3

1

+= ... 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)

Sign up to request clarification or add additional context in comments.

Comments

1

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)

1 Comment

Thank, I missed parentheses . I tried a[i] || 0 + random_number and it didn't work.
0

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

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

Comments

Your Answer

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.