why is the following code showing undefined? Are we not allowed to create an array with a single value? Putting two values won't show this error. Is this a problem with Javascript?

<script>
var tech = new Array(21);
alert(tech[0]);
</script>
share|improve this question

57% accept rate
feedback

4 Answers

new Array(21) creates an array with a length of 21. If you want to create a single-value array, consisting of a number, use square brackets, [21]:

var tech = [ 21 ];
alert(tech[0]);

If you want to dynamically fill an array, use the .push method:

var filler = [];
for(var i=0; i<5; i++){
    filler.push(i); //Example, pushing 5 integers in an array
}
//Filler is now equivalent to: new Array(0, 1, 2, 3, 4);

When the Array constructor receives one parameter p, which is a positive number, an array will be created, consisting of p elements. This feature is can be used to repeat strings, for example:

var repeat = new Array(10);
repeat = repeat.join("To repeat"); //Repeat the string 9x
share|improve this answer
This is incorrect. The array doesn't contain any elements, rather it has a length property of that value. There is a difference: a=Array(3); b=[1,2,3]; 1 in b === true; 1 in a === false – davin Oct 20 '11 at 9:32
@Rob W - but the thing is I am dynamically creating arrays in a loop, some are single valued, some are not. So whats the better way? – Imran Omar Bukhsh Oct 20 '11 at 9:36
You're still incorrect after your edit. They are not initialised as undefined. They simply don't exist. – davin Oct 20 '11 at 9:36
@ImranOmarBukhsh Use the .push method to fill the array. See my updated answer. – Rob W Oct 20 '11 at 9:40
feedback

The above example defining an array called tech with 21 positions. You have to difine it like that

var tech = new Array('21');
alert(tech[0]);
share|improve this answer
feedback

by new Array(21) you're actually creating an array with 21 elements in it.

If you want to create an array with single value '21', then it's:

var tech = [21];
alert(tech[0]);
share|improve this answer
feedback
up vote 2 down vote accepted

guys the answer was as simple as this:

<script>
var tech = new Array();
tech.push(21);
alert(tech[0]);
</script>
share|improve this answer
feedback

Your Answer

 
or
required, but never shown
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.