0

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] + ", ");
              }
3
Contributors
5
Replies
7
Views
5 Years
Discussion Span
Last Post by sepp2k
0

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

0

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

0

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?

0

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

0

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.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.