I’m trying to create a 2D array in JS that I can return from my method. I basically want to do something like this:
var msg[][4] = [][entryID, entryName, entryURL, entryDesc];
for (var i = 0, len = bookmarks.length; i < len; i++) {
var id = bookmarks[i].getElementsByTagName('id')[0].firstChild.nodeValue;
var name = bookmarks[i].getElementsByTagName('name')[0].firstChild.nodeValue;
var url = bookmarks[i].getElementsByTagName('url')[0].firstChild.nodeValue;
var desc = bookmarks[i].getElementsByTagName('desc')[0].firstChild.nodeValue;
msg[i][entryID] = id;
msg[i][entryName] = name;
msg[i][entryURL] = entryURL;
msg[i][entryDesc] = entryDesc;
}
The first line msg[][4] throws an error. I’m not sure if or how I can do something like that. Thanks.
If
entryIDetc is supposed to be a string, then I think what you actually want is an array of objects:You can then access e.g. the second entry with
msg[1].entryID. Instead of creating an object, you can simply create an array as well, but using an object is more descriptive in my opinion.JavaScript does not have multi-dimensional arrays. What you can create are arrays of arrays (of arrays…) or arrays of objects (of arrays/objects …). Arrays in JavaScript are dynamic, therefore it is not necessary to initialize them with any size. Just keep adding whatever vaue you want to the array.