The forums ran from 2008-2020 and are now closed and viewable here as an archive.

Home Forums JavaScript What am I doing wrong? Reply To: What am I doing wrong?


Thinking further about it, I wouldn’t do it your way. Initializing the Array is too lengthy in my opinion. You can use Array literals like so:

var options = [
    "one", "two", "three", "four", "five", "six"

No need to remember at which index you are adding the items.

Inside your for-loop you are querying and modifying the DOM in every iteration. That can be SLOW. It’s better to prepare the changes in a variable and change the DOM once:

var newHTML = "";
// for-loop: append new items to newHTML
document.getElementById("demo").innerHTML = newHTML;

Also, you have a fixed upper index in your for-loop, which can later be the reason for bugs

for (var i = 0; i < 6; i++)

This is better:

for (var i = 0; i < options.length; i++)

However, there is a functional alternative. In jQuery and Javascript 1.6+, the Array objects has the map-function, which essentially calls a function for every item and returns an array with all the results. Which is exactly what you are trying to do – map the names of the options “one”, “two”, … to actual HTML code “<option>one</option>”, … . function(value) { return "<option>" + value + "</option>" })

Afterwards, you can just join the resulting array with .join(separator)

Take a look here: