-2

I'm trying to push 1 -> 10 into my "array1" though I'm sure that it's not working.

array1 = ["123", "abc", "string", "text", "test", "ok"]
                 while (i <= 10){
                    array1.push(i)
                    i++
                 }
    document.getElementById("p0").innerHTML = document.getElementById("p0").innerHTML + " | " + array[Math.floor((Math.random() * array.length))]

p0's innerhtml stays as "Random Array Item:" and does not change, though when I remove the while loop it seems to work fine, example output, "Random Array Item: | test | text | abc | abc | text | abc"

Liam
  • 27,717
  • 28
  • 128
  • 190
Andrew
  • 3
  • 2
  • Would you like to put numbers as a key or concatenate into the values? – Igor O Nov 16 '17 at 08:12
  • 1
    Looking at your variable names, this can't possibly work. See [this JSFiddle](https://jsfiddle.net/pbdevch/wv5j9gtw/) – Filnor Nov 16 '17 at 08:12
  • Your code works just fine, except you've used `array` instead of `array1` on the last line of the code snippet. – 31piy Nov 16 '17 at 08:17
  • Press run snippet, it tells you what the problem is... I suggest you learn how to [debug javascript](https://stackoverflow.com/questions/988363/how-can-i-debug-my-javascript-code). – Liam Nov 16 '17 at 08:24

3 Answers3

2

You have an error when referencing your array, as you are using array but your array is named array1. You need to change that in order to work:

i=0;
array1 = ["123", "abc", "string", "text", "test", "ok"];
while (i <= 10){
    array1.push(i);
    i++;
}
document.getElementById("p0").innerHTML = document.getElementById("p0").innerHTML + " | " + array1[Math.floor((Math.random() * array1.length))];
<p id="p0">Random Array Item</p>
Filnor
  • 1,290
  • 2
  • 23
  • 28
0

If the use case is just to push 1...10 into a new array, this will work.

var array1 = ["123", "abc", "string", "text", "test", "ok"],    
[1,2,3,4,5,6,7,8,9,10].forEach(function(i){
 array1.push(i);
});

document.getElementById("p0").innerHTML = document.getElementById("p0").innerHTML + " | " + array1[Math.floor((Math.random() * array1.length))];
MartinWebb
  • 1,998
  • 1
  • 13
  • 15
0

Follow some adjustments:

var i = 0;
array1 = ["123", "abc", "string", "text", "test", "ok"]
             while (i <= 10){
                array1.push(i)
                i++
             }
document.getElementById("p0").innerHTML = document.getElementById("p0").innerHTML + " | " + array1[Math.floor((Math.random() * array1.length))]

basically, you just need to change the last variable from array to array1.

Igor O
  • 301
  • 1
  • 6
  • 26