supersize
supersize

Reputation: 14833

use variable inside an array

I would like to know how I can access the var randomnumber inside that cubesmixed-Array This is the code:

var cubesmixed = [paper.rect(randomnumber, randomnumber, 0, 0), 
                  paper.rect(randomnumber, randomnumber, 0, 0), 
                  ... going on till over 100]; 
var randomnumber;
for(var i = 0; i < 143; i++) {
var randomnumber=Math.floor(Math.random()*2000);
    cubesmixed[i].animate({ width: 25, height: 25 }, 500, "bounce");
    console.log(i);
}

inside that array the value of randomnumber is 0. How can I do this?

Cheers

Upvotes: 0

Views: 97

Answers (1)

nnnnnn
nnnnnn

Reputation: 150080

You declare randomnumber twice, both times after using it in the cubesmixed declaration. So currently each time you actually use randomnumber it'll be undefined. Currently you set randomnumber equal to a randomly generated number inside your for loop, but you don't actually use it within the loop.

If your actual goal to create an array of 143 items each of which have different random coordinates then you can do this:

var cubesmixed = []; 
var cube;
for(var i = 0; i < 143; i++) {
  cube = paper.rect(Math.floor(Math.random()*2000), Math.floor(Math.random()*2000), 0, 0);
  cube.animate({ width: 25, height: 25 }, 500, "bounce");
  cubesmixed.push(cube);
}

On the other hand if you just want all the items to have the same coordinates as each other move your current line:

var randomnumber=Math.floor(Math.random()*2000);

...from inside the loop to before the cubesmixed declaration.

Upvotes: 1

Related Questions