Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a single value array in JavaScript

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> 
like image 945
Imran Omar Bukhsh Avatar asked Oct 20 '11 09:10

Imran Omar Bukhsh


People also ask

Does array [- 1 work in JavaScript?

As others said, In Javascript array[-1] is just a reference to a property of array (like length ) that is usually undefined (because it's not evaluated to any value).

How can you create an array in JavaScript?

Using an array literal is the easiest way to create a JavaScript Array. Syntax: const array_name = [item1, item2, ...]; It is a common practice to declare arrays with the const keyword.

How do you create an array?

You can make an array of int s, double s, or any other type, but all the values in an array must have the same type. To create an array, you have to declare a variable with an array type and then create the array itself. Array types look like other Java types, except they are followed by square brackets ( [] ).


2 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: [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 
like image 126
Rob W Avatar answered Sep 22 '22 08:09

Rob W


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]); 
like image 20
Samuli Hakoniemi Avatar answered Sep 25 '22 08:09

Samuli Hakoniemi