DarkLightA
DarkLightA

Reputation: 15662

Why is this javascript object code not working?

var house = new Object(floors: "4", color:"red", windows:"lots", bathrooms:"3");
var result ="";
for (var i in house)
{
    result +="house." + i + " is " + house.i + ".<br />";
}
document.body.innerHTML += result;

I want to output house.floors is 4.<br />house.color is red.<br />and so on.

Upvotes: 0

Views: 279

Answers (2)

Pointy
Pointy

Reputation: 413712

Curly brackets:

var house = {floors: "4", color:"red", windows:"lots", bathrooms:"3"};

There's rarely a need (in fact I can't think of a reason) to use an explicit Object constructor call; just use {} for a new, plain, empty Object instance, and [] for a new, plain, empty Array instance. For objects with initial properties, use the "name:value" syntax like you did (except in curly brackets).

Upvotes: 2

Quentin
Quentin

Reputation: 943209

The Object constructor doesn't work like that. Use an object literal instead.

var house = { floors: "4", color:"red", windows:"lots", bathrooms:"3" }

Additionally house.i will reference the i property, not the property with the name that is stored in the string i, you want house[i].

Upvotes: 3

Related Questions