'Assigning properties to array gives length 0 in javascript [duplicate]
We can assign properties to an array, but why the length in this case is 0? See the code attached
var person = []
person.fname = "Mr. Brown"
person.lname = "White"
person.length // gives 0 why?
Solution 1:[1]
Array stores elements. If you want to call person.name= "Mr.Brown" You can actually implement it by:
//Initialize the variable
let person = [];
//Specify the object that will be pushed to the Array 'Person'
let objectToPush = {name: 'Mr. Brown'};
//Push the object
person.push(objectToPush);
//Get Length
console.log(person.length); //<--- Will return 1;
//Call the name property inside the object
console.log(person[0].name); //<-- returns 'Mr.Brown'
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | jgandrade |
