Code Academy says there are 2 ways to create objects in JavaScript.
1. object literal notation
var myObject = {
key: value,
key: value,
key: value
};
2. object constructor approach
var myObject = new Object();
Keys can then be added thus:
myObj["name"] = "Charlie";
myObj.name = "Charlie"; //shorthand for the first
Being asked to create 3 objects, I tried different ways to produce the objects with the same values but I am getting an error using the template provided above. My code is pasted below:
var object1 = {
1: 2,
7: 3,
4: 5
};
var object2 = new Object();
object2['1'] = 2;
object2['7'] = 3;
object2['4'] = 5;
var object3 = new Object();
object3.1 = 2;
object3.7 = 3;
object3.4 = 5;
Code Academy gave me an error and to figure out where exactly it was, I used Chrome's console. Tying each object creation separately on Chrome's console, object1 and object2 could be created but not object3 which produces the error: Uncaught SyntaxError: Unexpected number
Changing object3's code to (changing keys from numbers to strings):
var object3 = new Object();
object3.'1' = 2;
object3.'7' = 3;
object3.'4' = 5;
produces the error: Uncaught SyntaxError: Unexpected string
Is it possible to create object3 using this template/layout to produce values of object1 or can the key never be a number or string? A string but not a number for the key worked in creating object2.