Hi there,

I was trying different types of array initialisation in Javascript and the book that I was reading, said it is possible to initilaise an array with a speicified number of elements in it. However, I tried it and unfortunately, it didn't work. As you can see the code below, the array b should ONLY have 3 empty elements in it. But, that can add more than 3 elements into it.

             var b = new Array(3);

              //assigning values to the indexes of array b
              for(var i=1; i <= 6; i++){
                  b[i]= i;


                  alert(b.length);
                  println(b[i] + ", ");
              }

Recommended Answers

All 5 Replies

When you create the array it does only have 3 elements in it. That doesn't mean you can't add more to it.

JavaScript is not as strict as C# or probably java in terms of initializing an array with a specified number of elements.

I only want it to have three elements in it. Is there a way of doing that? Or Is javascript flexible and not caring so much like Java?

Then make sure that you only loop 3 times :) JavaScript is very flexible and not strict.

I only want it to have three elements in it.

Then put only three elements in it. That doesn't seem very hard to do. If you change your loop to

for(var i=1; i < b.length; i++) {
     b[i]= i;
}

It won't add any additional elements to it. Using b.length as the boundary instead of a magic number is much better code anyway because it's easier to understand and prevents many kinds of mistakes.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.