function setup() {
var names = [];
var name = {firstname: "", lastname: ""};
name.firstname = "John";
name.lastname = "Doe";
names.push(name);
name.firstname = "Bill";
name.lastname = "Smith";
names.push(name);
return names;
}
var temp = setup();
print temp[0].firstname;
I can't seem to figure out how to return an array of objects from a function. Any idea where I'm going wrong?
The problem is that the result stored in temp is the following:
[
{
firstname: "Bill",
lastname: "Smith"
},
{
firstname: "Bill",
lastname: "Smith"
}
]
document.write( temp[0].firstname )namesarray, and overwriting the properties of that object. it will mean you have duplicate entries of bill smith in the output array..push().var names = [{firstname: "john", lastname: "doe"}, {firstname: "bill": lastname: "smith"}];You can also pass multiple items to.push()at once.