0

Hey guys i dont see the fault on my Code.

I just want to add some calculate numbers into my array.

Just look at the array named "numberOfarrays". Why is the out-put look like that :

5050,2550,25,2050,25,20,1450,25,20...

and not like i thought:

50,25,20,14....

I am realy confused.

My Code:

<script>
    var a = [2,4,6,8,10,12,14,16,18,20];
    var sum= 0;//110
    for (var i = 0; i < a.length; i ++) {
        sum = sum+a[i]
    }
    alert(sum);
    var tmp = 100/sum;//0,909..
    alert(tmp);
    var arryPlaetze = [];

    for (var i = 0; i < a.length; i ++) {// 10 durchläufe
        arryPlaetze.push(Math.round(tmp*a[i])); 
    }
    var wheel =[];
    var lengthWheel = 100;
    var numberOfarrays =[];
    alert("numberOfarrays"+ numberOfarrays.toString());
    alert(arryPlaetze[1]);

    //Problem
    for (var i = 0; i < arryPlaetze.length; i++) {
        alert("zahler: "+i);
        alert("test "+Math.round(lengthWheel/arryPlaetze[i]));//50
        var tmp = Math.round(lengthWheel/arryPlaetze[i]);
        numberOfarrays.push(tmp);// fail why 5050 not 50,25


        document.write(numberOfarrays.toString());

    }

</script>

You can put the Code into a html to run it very easy.

2
  • 3
    Move document.write(numberOfarrays.toString()); outside of the loop. You're showing the contents of the array at every step. It'd be even better if you used your console for logging information. Commented Jan 12, 2017 at 17:01
  • thx very much. now i found my fault. Sometimes you need to writte to poeple to get a solution ^^ . Commented Jan 12, 2017 at 17:10

1 Answer 1

6

Move your document.write() outside of your loop. Right now it is printing the array every time, which results in

(50)(50,25)(50,25,20)(50,25,20,14)

But since there are no ()s, then it just prints as

505025502520...

Also as Mike C said it would be better for logging if you used console.log() instead of document.write().

Sign up to request clarification or add additional context in comments.

1 Comment

It would also be more effective for logging than "alerting."

Your Answer

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.