1

我有一个 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

4 回答 4

6

您可以使用索引:

new_people['11'] = 'John';
于 2013-03-22T13:24:54.070 回答
2

您只需要向对象添加一个键值:

people['11'] = "John";

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

people.key = "John";

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

people["~!#$#$#HV"] ="some value";
于 2013-03-22T13:25:27.443 回答
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"}
于 2013-03-22T13:32:28.117 回答
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]);  
};
于 2013-03-22T13:59:01.480 回答