I have the following code:
<html>
<body>
<div style="background-color: lightblue;" onClick="alert(myArray[0][1])">
this is a div
</div>
<script type="text/javascript">
var myArray = new Array();
myArray[0][0] = 0;
myArray[0][1] = 00012;
myArray[0][2] = 00006;
myArray[1][0] = 1;
myArray[1][1] = 00004;
myArray[1][2] = 00001;
</script>
</body>
</html>
When I click on the div, nothing happens; there's no alert. When I change the inside of alert to a string, such as 'test', however, then the alert box does come up.
What am I doing wrong? How can I get the value of an item in a multidimensional array?
Thanks!
The first line of your code:
var myArray = new Array();
...will create a new, single dimensional array, myArray, that has no elements. Then when you say:
myArray[0][0] = 0;
...you are trying to access a dimension that doesn't exist yet. That is, myArray[0] is undefined because although myArray is an array it doesn't have any elements yet - so myArray[0][0] is like saying undefined[0].
That's why you have to to assign myArray[0] to refer to a new array before you can access myArray[0][0]. The same thing applies to myArray[1], because JavaScript doesn't have multi-dimensional arrays per se, it has arrays of arrays. So this is what you need (for a minimal change to your existing code):
var myArray = [];
myArray[0] = [];
myArray[0][0] = 00012;
myArray[0][1] = 00012;
myArray[0][2] = 00006;
myArray[1] = [];
myArray[1][0] = 1;
myArray[1][1] = 00004;
myArray[1][2] = 00001;
Note that [] is equivalent to new Array().
An easier to read and type option is to create the sub-arrays via array literal syntax:
var myArray = [];
myArray[0] = [00012, 00012, 00006];
myArray[1] = [1, 00004, 00001];
Or, easiest of all (especially if these are hard-coded values) is creating the whole thing in one statement via a nested array literal (white-space is ignored):
var myArray = [
[00012, 00012, 00006],
[1, 00004, 00001]
];
(Note also that those leading zeros will disappear for numeric data: use strings ("00012" instead of 00012) if you want to retain the zeros.)
Write it out like this:
<div style="background-color: lightblue;" onClick="alert(myArray[0][1])">
this is a div
</div>
<script type='text/javascript'>
var myArray = [];
myArray.push([0, 00012, 00006]);
myArray.push([1, 00004, 00001]);
</script>
Edit
The problem is that when you write this:
var myArray = new Array();
myArray[0][0] = 0;
The first item in myArray is undefined, so you can't do anything with it. Using this method, you'd have to create the array first:
var myArray = new Array();
myArray[0] = new Array();
myArray[0][0] = 0;
But I think the method of using the square notation with push is cleaner.
This is how you declare a multi dimensional array:
MultiArray = new Array(2)
MultiArray [0] = new Array(2)
MultiArray [0][0] = "Tom"
MultiArray [0][1] = "scientist"
MultiArray [1] = new Array(2)
MultiArray [1][0] = "Beryl"
MultiArray [1][1] = "engineer"
Related
In the example below, the array2.length is only 10, while in my mind, it should be 13.
Why does the "string keyed" indexes not increase the length of the array?
I can store things and still access it, and the VS debugger shows that those arrays are being stored properly. So why is the length not increased?
var array2 = new Array();
array2["a"] = new Array();
array2["b"] = new Array();
array2["c"] = new Array();
for (var i = 0; i < 10; ++i)
array2[i] = new Array();
var nothing = "";
for (var i = 0; i < array2.length; ++i)
nothing = "";
Javascript arrays cannot have "string indexes". A Javascript Array is exclusively numerically indexed. When you set a "string index", you're setting a property of the object. These are equivalent:
array.a = 'foo';
array['a'] = 'foo';
Those properties are not part of the "data storage" of the array.
If you want "associative arrays", you need to use an object:
var obj = {};
obj['a'] = 'foo';
Maybe the simplest visualization is using the literal notation instead of new Array:
// numerically indexed Array
var array = ['foo', 'bar', 'baz'];
// associative Object
var dict = { foo : 42, bar : 'baz' };
Because the length is defined to be one plus the largest numeric index in the array.
var xs = [];
xs[10] = 17;
console.log( xs.length ); //11
For this reason, you should only use arrays for storing things indexed by numbers, using plain objects instead if you want to use strings as keys. Also, as a sidenote, it is a better practice to use literals like [] or {} instead of new Array and new Object.
You're not adding items to the array; you're adding properties to the Array object.
As said above, use object for associative arrays.
If you don't you won't necessarily notice you're doing it wrong, until you innocently use "length" as an array index :
var myArray = [];
myArray["foo"] = "bar"; //works
console.log(myArray["foo"]) //print "bar"
myArray["length"] = "baz" //crash with a "RangeError: Invalid array length"
That is because you are replacing the length attribute of an array with a String, which is invalid.
"string keyed" indexes are not indexes at all, but properties. array2["a"] is the same as saying array2.a. Remember that you can set properties on any kind of variable in javascript, which is exactly what you're doing here.
You can push object to array, it will automatically get indexed (integer). If you want to add index as you want then you want to make it as object
If you want to use an object's properties as if they were like instances of a string indexed array, the work around for the length is:
var myArray = new Array();
myArray["a"] = 'foo';
myArray["b"] = 'bar';
myArray["c"] = 'baz';
let theLength = Object.keys(myArray).length
I'm running a js code and in some part of it there is a definition of an array which I don't get what it means , it looks like this :
var myArray = new Array();
myArray[myNum] = new Array();
myArray[myNum].push(value1);
I don't get why there is an index of the array at the second line , is it a two dimensional array ? I'll appreciate if you can help me with this. thanks
var myArray = new Array();
Creates an array.
myArray[myNum] = new Array();
Creates an array in myArray's myNum index.
myArray[myNum].push(value1);
Stores valuea1 into the array (adds the element at the last, in this case at 0-th index) stored in myArray[myNum].
Yes, your assumption is right - after the execution of the three statements a two dimensional array is created, which looks something like this -
[....., [value1], ......] // the inner array is stored at "myNum" index
To access value1, you can now do -
myArray[myNum][0];
See the doc for push.
This code just creates an array with an array at index myNum. Lets break the code down.
var myArray = new Array();
//Create a new array
myArray[myNum] = new Array();
//At index 'myNum' which is a variable presumably holding an index - create a new array
myArray[myNum].push(value1);
//push variable `value1` to the new array at index myNum of myArray.
Let me try to explain your code....
Explanation:
var myArray = new Array(); // (1)
myArray[myNum] = new Array(); // (2)
myArray[myNum].push(value1); // (3)
(1) This creates a new empty array . It could be 1D, 2D, 3D. Currently it has nothing. At this point you array should look like this..
myArray= [];
(2) This creates another empty Array in "myArray" at index "myNum". Let us assume myNum=5;
So
myArray[5] = new Array();
Will give
myArray =[[]];
(3) This will push value1 into myArray at index "myNum". Let us again assume myNum=5 and value1 = 1,2,3;
So
myArray[5].push(1,2,3);
Will give
myArray=[[1,2,3]]
DEMO IN A FIDDLE
In the example below, the array2.length is only 10, while in my mind, it should be 13.
Why does the "string keyed" indexes not increase the length of the array?
I can store things and still access it, and the VS debugger shows that those arrays are being stored properly. So why is the length not increased?
var array2 = new Array();
array2["a"] = new Array();
array2["b"] = new Array();
array2["c"] = new Array();
for (var i = 0; i < 10; ++i)
array2[i] = new Array();
var nothing = "";
for (var i = 0; i < array2.length; ++i)
nothing = "";
Javascript arrays cannot have "string indexes". A Javascript Array is exclusively numerically indexed. When you set a "string index", you're setting a property of the object. These are equivalent:
array.a = 'foo';
array['a'] = 'foo';
Those properties are not part of the "data storage" of the array.
If you want "associative arrays", you need to use an object:
var obj = {};
obj['a'] = 'foo';
Maybe the simplest visualization is using the literal notation instead of new Array:
// numerically indexed Array
var array = ['foo', 'bar', 'baz'];
// associative Object
var dict = { foo : 42, bar : 'baz' };
Because the length is defined to be one plus the largest numeric index in the array.
var xs = [];
xs[10] = 17;
console.log( xs.length ); //11
For this reason, you should only use arrays for storing things indexed by numbers, using plain objects instead if you want to use strings as keys. Also, as a sidenote, it is a better practice to use literals like [] or {} instead of new Array and new Object.
You're not adding items to the array; you're adding properties to the Array object.
As said above, use object for associative arrays.
If you don't you won't necessarily notice you're doing it wrong, until you innocently use "length" as an array index :
var myArray = [];
myArray["foo"] = "bar"; //works
console.log(myArray["foo"]) //print "bar"
myArray["length"] = "baz" //crash with a "RangeError: Invalid array length"
That is because you are replacing the length attribute of an array with a String, which is invalid.
"string keyed" indexes are not indexes at all, but properties. array2["a"] is the same as saying array2.a. Remember that you can set properties on any kind of variable in javascript, which is exactly what you're doing here.
You can push object to array, it will automatically get indexed (integer). If you want to add index as you want then you want to make it as object
If you want to use an object's properties as if they were like instances of a string indexed array, the work around for the length is:
var myArray = new Array();
myArray["a"] = 'foo';
myArray["b"] = 'bar';
myArray["c"] = 'baz';
let theLength = Object.keys(myArray).length
I want to declare a hashmap in javascript with <String, String array> instead of <String,Integer>. How can that be done ?
If you plan to use a javascript Array object, be aware that an array index can only be accessed via integers.
var arr = [];
arr['person'] = 'John Smith';
alert(arr.length); // returns 0, not an array anymore;
and
var arr = [];
arr[0] = 'John Smith';
alert(arr.length); // returns 1, still an array;
The above would work in javascript, but var arr actually is not an array object anymore. You cannot sort it, for example.
So for you hashmap you could do
var map = new Object();
map['person'] = [];
map['person']['test'] = 'myvalue';
map['person']['test2'] = 'myvalue2';
alert(map['person']['test']);
What is the difference between each of the following array definitions.
var myArray = [];
var myArray = {};
var myArray = new Array();
The first and third are equivalent and create a new array. The second creates a new empty object, not an array.
var myArray = []; //create a new array
var myArray = {}; //creates **a new empty object**
var myArray = new Array(); //create a new array
var myObject = {}; is equivalent to var myObject = new Object();
So, the second example is not an Array but a general Object.
This can get confusing as Array is a class and Object is a class - more precisely Array is a sub-class of Object. So, by and large, Object semantics are applicable to an Array:
var o = [];
o.push('element1');
o.push('element2');
o['property1'] = 'property value'; // define a custom property.
console.log(o.property1);
console.log(o.length); // Outputs '2' as we've only push()'ed two elements onto the Array