开发者

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 hou开发者_运维问答se.floors is 4.<br />house.color is red.<br />and so on.


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].


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).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜