Reputation: 351
My javascript code looks something like this:
var balls = [];
var size = 10;
for(var i=0; i<size; i++){
balls.push({
x: 100,
y: 100,
radius: getRandomInt(20,50),
mass : //here i want mass to have same value as that of radius.
})
}
As I'm pushing newly created objects in my array of objects, I want the variables radius and mass to have same random number returned by getRandomInt(20,50)
.
How do I achieve that? Writing mass: radius
or mass: this.radius
doesn't seem correct.
Thanks!
Upvotes: 1
Views: 68
Reputation: 11342
Store(assign) the random number to a temp variable then use it within the current scope.
var balls = [];
var size = 10;
for(var i=0; i<size; i++){
var temp = getRandomInt(20,50);
console.log('this temp: ' + temp);
balls.push({
x: 100,
y: 100,
radius: temp,
mass : temp
})
}
function getRandomInt(min,max){
return Math.floor(Math.random() * (max - min + 1) + min);
}
Upvotes: 3
Reputation: 904
use a global variable and assign it to that when you run the function
var balls = [];
var size = 10;
var rndNum=0;
for(var i=0; i<size; i++){
getRandomInt(20,50);
balls.push({
x: 100,
y: 100,
radius: rndNum,
mass : rndNum
})
}
function getRandomInt(x,y){
rndNum=//do random math and assign to rndNum
}
Upvotes: -1