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>
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).
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.
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 ( [] ).
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
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]);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With