0

Why does the console print "undefined" when I print index 3? I'm trying to set index 3 to false and after 7 secs set it to true.

I've tried to change "nr", index 2, with success trying to narrow down the problem.

if (Math.random() < 0.005) {
    nx = Math.random()*1000; //index0
    ny = 200; //index1
    nr = 5;//index2
    var nfall = false; //index3
    Apples.push([nx,ny,nr,nfall]); //simply inserting 'false' into index 3 doesn't work either.

    setTimeout(function(){ Apples[2][2] = 500; Apples[2][3] = true;}, 7000); //3rd apple

    console.log("New circle, x:"+Apples[2][0]+" y:"+Apples[2][1]+" nr:"+Apples[2][2] +" nfall:"+Apples[2[3]]);
//What works - in 7 seconds "nr" is updated from 5 to 500, but nfall is still undefined and NOT = true

Initially I expect the output of false from index 3 "nfall" then I expect the output of true from index 3 "nfall" after 7 secs.

Thank you

1
  • console.log("New circle, x:"+Apples[2][0]+" y:"+Apples[2][1]+" nr:"+Apples[2][2] +" nfall:"+Apples[2][3]); plz change in Apples[2[3]] to Apples[2][3] Commented Apr 17, 2019 at 3:20

2 Answers 2

1

In your console.log call, you're accessing the array like this:

Apples[2[3]]

But it should be

Apples[2][3]

In the first version, you're accessing index 3 of the number 2 which actually is not an error, just undefined.

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

Comments

0

Your issue is the last part - you're accessing Apples[2[3]] which doesn't exist, and it's invalid syntax. You want to get the third item in Apples (which is an array), then access the fourth item of that array - do it simply with `Apples[2][3]:

const Apples = [1, 2, [3, 4, 5, 6]];
console.log(Apples[2][3]);

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.