8 bit gamer
8 bit gamer

Reputation: 29

javascript for loop array

can someone please explain how I add/subtract one part of an array (xpos) to another (speed) and then put the answer back into the xpos array. ive tried for loops but can get it to work. is there another way?

<script>
var xpos = [];
var speed = [];
for (i=0;i<10;i++) {
vx = Math.floor((Math.random() * 5) + 1);
xpos.push(vx);
vy = Math.floor((Math.random() * 100) + 10);
speed.push(vy);
}
document.write(xpos+"<br>");
document.write(speed);

</script>

Upvotes: 0

Views: 145

Answers (1)

mjgpy3
mjgpy3

Reputation: 8937

I'm pretty sure you can just use:

var xpos = [];
var speed = [];
for (i=0;i<10;i++) {
  vx = Math.floor((Math.random() * 5) + 1);
  xpos[i] = vx;
  vy = Math.floor((Math.random() * 100) + 10);
  speed[i] = vy;
}
document.write(xpos+"<br>");
document.write(speed);

In JavaScript, arrays don't behave like indexed arrays in many other languages. You don't have to specify a size and you can assign values to arbitrary indices using angle brackets, like so:

xpos[i] = vx;
...
speed[i] = vy;

Your question isn't entirely clear, but, if I'm understanding it right, you could simply do:

xpos[i] = xpos[i] <op> speed[i];

where <op> is + or -

Of course, if you're doing all this in the same loop it doesn't make a lot of sense to save to xpos and then immediately overwrite it with the difference. So you could just say:

speed[i] = vy;
xpos[i] = vx <op> speed[i];

Upvotes: 1

Related Questions