简体   繁体   English

多次设置Javascript属性

[英]Setting Javascript Properties Multiple Times

I'm currently learning javascript and I came across this rather odd behavior when setting a property multiple times. 我目前正在学习javascript,并且在多次设置属性时遇到了这种相当奇怪的行为。 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? 这种行为有一些奇怪的javascript原因吗? 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: ECMAScript 5严格模式修复了,所以下面会抛出一个错误:

"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. @Blender:我猜show是他的库中的一个方法,它遍历每个属性并以其相关值打印出来。

Non-strict JavaScript allows objects to contain multiple properties with the same name. 非严格JavaScript允许对象包含具有相同名称的多个属性。 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";

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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