JavaScript arrays braces vs brackets - javascript

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

Related

Convert String to already declared object in JavaScript?

I have this code:
//Arguments are unique.
var Object1 = new Object(argument,argument,argument);
var Object2 = new Object(argument,argument,argument);
var Object3 = new Object(argument,argument,argument);
//...
var Object100 new Object(argument,argument,argument);
function convert(){
var array = ["Object1","Object56"];
// Manipulate values in array above as if they were the objects already
//declared above this function, like acessing "Object56.argument" property.
}
I need to convert the the strings in the array to the objects that have already been declared, in order to manipulate the objects properties (which are converted from the arguments) in a function. I realize I'm basically turning JS objects into a database which is probably a bad idea but I was wondering if there's a solution to this? They way the values in the array are chosen is fairly complex and I think it would detract from the question, but they are randomly generated more or less.
Instead of storing each object as a separate variable, create a map:
var objectMap = {
Object1: new Object(argument, argument, argument),
Object2: new Object(argument, argument, argument),
// ...
Object100: new Object(argument, argument, argument)
};
The mapping would then be easy enough.
You can either do it manually:
var array = ['Object1', 'Object2'];
var objects = [];
for(var i = 0; i < array.length; i++) {
var key = array[i];
objects.push(objectMap[key]);
}
Or (if you're supporting ES5) use the map function:
var array = ['Object1', 'Object2'];
var objects = array.map(function (key) {
return objectMap[key];
});

How to access value in multidimensional array?

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"

javascript push multidimensional array

I've got something like that:
var valueToPush = new Array();
valueToPush["productID"] = productID;
valueToPush["itemColorTitle"] = itemColorTitle;
valueToPush["itemColorPath"] = itemColorPath;
cookie_value_add.push(valueToPush);
the result is [];
what am i do wrong?
Arrays must have zero based integer indexes in JavaScript. So:
var valueToPush = new Array();
valueToPush[0] = productID;
valueToPush[1] = itemColorTitle;
valueToPush[2] = itemColorPath;
cookie_value_add.push(valueToPush);
Or maybe you want to use objects (which are associative arrays):
var valueToPush = { }; // or "var valueToPush = new Object();" which is the same
valueToPush["productID"] = productID;
valueToPush["itemColorTitle"] = itemColorTitle;
valueToPush["itemColorPath"] = itemColorPath;
cookie_value_add.push(valueToPush);
which is equivalent to:
var valueToPush = { };
valueToPush.productID = productID;
valueToPush.itemColorTitle = itemColorTitle;
valueToPush.itemColorPath = itemColorPath;
cookie_value_add.push(valueToPush);
It's a really fundamental and crucial difference between JavaScript arrays and JavaScript objects (which are associative arrays) that every JavaScript developer must understand.
Use []:
cookie_value_add.push([productID,itemColorTitle, itemColorPath]);
or
arrayToPush.push([value1, value2, ..., valueN]);
In JavaScript, the type of key/value store you are attempting to use is an object literal, rather than an array. You are mistakenly creating a composite array object, which happens to have other properties based on the key names you provided, but the array portion contains no elements.
Instead, declare valueToPush as an object and push that onto cookie_value_add:
// Create valueToPush as an object {} rather than an array []
var valueToPush = {};
// Add the properties to your object
// Note, you could also use the valueToPush["productID"] syntax you had
// above, but this is a more object-like syntax
valueToPush.productID = productID;
valueToPush.itemColorTitle = itemColorTitle;
valueToPush.itemColorPath = itemColorPath;
cookie_value_add.push(valueToPush);
// View the structure of cookie_value_add
console.dir(cookie_value_add);

declare hashmap in javascript with <String,String array>

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 does [] mean in JavaScript?

In the following javascript code there is [] being assigned as the value of a variable, what does it mean?
var openTollDebug = [];
it is an array literal. It is not quite the same as declaring new Array() - the Array object can be overwritten in JavaScript, but the array literal can't. Here's an example to demonstrate
// let's overwrite the Array object
Array = function(id) {
this.id = id;
}
var a = new Array(1);
var b = [];
console.log(a.hasOwnProperty("id")); // true
console.log(b.hasOwnProperty("id")); // false
console.log(a.push); // false, push doesn't exist on a
console.log(b.push); // true, but it does on b
b.push(2);
console.log(b); // outputs [2]
It means an array.
var openTollDebug = [];
declares the openTollDebug variable and initializes it to an empty array. To put elements into the array you could do the following:
var stringArray = ['element1', 'element2', 'element3'];
alert(stringArray[1]); // displays 'element2'
var numberArray = [1, 2, 3, 4];
alert(numberArray[2]); // displays 3
var objectArray = [{ name: 'john' }, { name: 'peter' }, { name: 'tom' }];
alert(objectArray[1].name); // displays 'peter'
It's an empty array, and is equal to
var openTollDebug = new Array();
It is shorthand for empty array. Same as new Array().
Also {} is an empty object. Objects are like hashtables in Js so you can use it as a dictionary.
It creates an empty array.
This is a good way to have a non-null object.
In JavaScript, it is then very easy to add functions and properties to that object. For example:
openTollDebug.title = 'hello world';
openTollDebug.show = function(){alert('Debug');};
As an array, you can add items:
openTollDebug.push('added item');
openTollDebug[3] = 'just add anywhere';
Many languages have constructs for literals. The [] is an Array literal.
var openTollDebug = [];
is the same as
var openTollDebug = new Array();
Just know that using [] preferred for performance reasons.
There are other literals like Object literals
var MyObject = {
name:'default',
age:22,
hobbies:["golf","video games","otherstuff"]
}
Notice the array literal with data. The [] creates an empty array.
Try to use literals due to performance. You dont write
var obj = new Object({name: 'John'})
You just write
var obj = {name: 'John'}
You also dont write
button.onclick = new Function("alert('Clicked!')");
You write
button.onclick = function () { alert('Clicked') }
And here's a link to a nice blog post about it
var b = [] //it is an array literal.

Categories