向对象添加新属性

时间:2013-03-22 13:23:35

标签: javascript

我有一个javascript对象,我将其用作具有键值对的地图类型。

当从控制器注入值时,会发生此映射的填充:

var people = {"2":"Brad","3":"Antonio","5":"Stacy","6":"Marry","1":"Jim"}

我想创建一个新对象但是还有一个条目,即伪代码

var new_people = people + {11: "John"}

我首先尝试将人们复制给新人:

new_people.\"11\" = "John"

new_people."11" = "John"

两者都会产生失败。虽然任何字符串而不是数字,但

new_people.anystring = "John"

var new_people = {"2":"Brad","3":"Antonio","5":"Stacy","6":"Marry","1":"Jim", "anystring":"John"}

4 个答案:

答案 0 :(得分:6)

您可以使用索引:

new_people['11'] = 'John';

答案 1 :(得分:2)

您只需要为对象添加键值:

people['11'] = "John";

如果密钥是有效的标识符名称(不是数字),您可以使用它:

people.key = "John";

当索引不是有效的变量名时,必须使用索引:

people["~!#$#$#HV"] ="some value";

答案 2 :(得分:2)

您将遇到问题,因为变量在存储对象时会保留引用。通过改变new_people,你也在改变人们。

var people = {"1":"James"}
console.log(people);       // Object {1: "James"}
var new_people = people;
new_people["2"] = "Jimmy";
console.log(people);       // Object {1: "James", 2: "Jimmy"}
console.log(new_people);   // Object {1: "James", 2: "Jimmy"}

您需要首先克隆对象,然后改变克隆,以免影响原始对象。

一种简单的方法是使用underscore.js extend()方法,如下所示:

var new_people = _.extend({}, people, {"2": "Jimmy"});
console.log(people);       // Object {1: "James"}
console.log(new_people);   // Object {1: "James", 2: "Jimmy"}

或类似地,使用jQuery extend(),如下所示:

var new_people = $.extend({}, people, {"2": "Jimmy"});
console.log(people);       // Object {1: "James"}
console.log(new_people);   // Object {1: "James", 2: "Jimmy"}

答案 3 :(得分:0)

@Gandalf StormCrow这是一段代码:jsfiddle

var people = {"2":"Brad","3":"Antonio","5":"Stacy","6":"Marry","1":"Jim"};

var newpeople = {"11": "John"};
jQuery.extend(people, newpeople);
//Now: people = {"2":"Brad","3":"Antonio","5":"Stacy","6":"Marry","1":"Jim","11": "John"}

for(var i in people){
  alert(people[i]);  
};