Array declaration in javascript [duplicate]

0

When I define an object like this:

Donotshowerror:

ButwhenIdeclarethisobjecttobeanarray:

Thisundefinedvariableerrorpopsup:

    
asked by anonymous 03.01.2018 / 18:43

2 answers

0

To define the first element of an array, in cars[0] , you must first declare the array cars = []; or cars = new Array(); .

var cars = [];
cars[0] = {
    a: "Saab",
    b: "Volvo",
    c: "BMW"
}
console.log(cars);

var cars2 = new Array();
cars2[0] = {
    a: "Saab",
    b: "Volvo",
    c: "BMW"
}
console.log(cars2);   
    
03.01.2018 / 18:48
0

The error is that there is no array cars . You can create it this way:

let cars = new Array({
    a: "Saab",
    b: "Volvo",
    c: "BMW"
});
console.log(cars);
    
03.01.2018 / 18:49