2

Im very much a javscript beginner and have gone through books and online forums such as this one but can't figure this out.

I have an array that is

var n=[1,1,1,1,5,5,5,5];

What the elements/numbers are are the number of times a ball wil bounce. so at n[0] to n[3] the ball will bounce once, and n[4] to n[7] it will bounce 5 times.

I want to write this logic, but am not sure how...

I started with

var x = n[];
n = 0;
while (x < 3, x++) {
 n = n[0];
 n[]++;
}
for (x = 3) {
 x++;
 n = 1;
 n[]++;
}
while (x > 3) {
 n = 5;
}

But I Know that this is incorrect. I am not sure how to proceed with this, could someone pelase help me?

Thank you!

Esailija
140k24 gold badges280 silver badges328 bronze badges
asked Jun 20, 2012 at 15:22
2
  • 2
    could you add comments to the code so we can see your logic? Commented Jun 20, 2012 at 15:25
  • 1
    Maybe you should read again about the syntax of for and of while? Commented Jun 20, 2012 at 15:27

1 Answer 1

2

It should be this way:

var x = [];
for(var i = 0; i < 8; i++)
 x[i] = i <= 3 ? 1 : 5;

Or, you can break it down the way you wrote to:

var x = [];
var i = 0;
while (i < 3) {
 x[i++] = 1;
}
for (i = 4; i < 8; i++)
 x[i] = 5;

You should read more about loop statements in javascript, and for the first way it is called ternary operator or conditional operator.

answered Jun 20, 2012 at 15:26
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! (I've never responded or used stackoverflow so I'm now sure if I'm responding/replying correctly in a way thaty ou'll see this)

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.