简体   繁体   中英

Setting Javascript Properties Multiple Times

I'm currently learning javascript and I came across this rather odd behavior when setting a property multiple times. For example:

var duck = {feet: 1, feet: 2}

On running

show(duck)

I get

{feet:2}

Is there some weird javascript reason for this behavior? Why is no error thrown?

You cannot have multiple properties of the same name in an object, but the language lets it pass silently. That's a flaw in the language. ECMAScript 5 strict mode fixed that, so the following will throw an error:

"use strict";
var duck = {feet: 1, feet: 2}
// SyntaxError: Duplicate data property in object literal not allowed in strict mode 

I kind of agree it would make sense to throw an error here. I think that the parser just expands the object declaration into a series of statements, so no part of it is actually invalid.

duck.feet = 1;
duck.feet = 2;

@Blender: I'm guessing show is a method among his libraries that steps through each property and prints it out with its associated value.

Non-strict JavaScript allows objects to contain multiple properties with the same name. When the same name is used multiple times, only the last declaration is used. Strict mode requires that all property names are unique.

"use strict";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM