-1

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>
asked Feb 21, 2015 at 13:18

1 Answer 1

1

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];
answered Feb 21, 2015 at 13:22
Sign up to request clarification or add additional context in comments.

1 Comment

many thanks for the quick reply. you made me look at my code and ive been doing it wrong. xpos[i] = xpos[i] <op> speed[i]; perfect.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.