假设我有一个对象数组,我希望它们有时可以作为哈希访问(更改它们的值,呃?),有时打印。
var test = { members : [] };
test.addMember = function(name, value) {
this.members[name] = { name : name, value : value };
this.members[name].toString = function() {
return this.name + " has a " + this.value; };
};
test.toString = function() {
return this.members.join(" and ");
};
test.addMember("a", "a value");
test.addMember("b", "b value");
alert(test);
我的目标是让test.toString()返回:
a has a value and b has b value
或者你有什么。我正在阅读MDN,似乎JavaScript 1.8.5(或某些子目标)将有一个调用toString()的join()。我被困了吗?
谢谢!
编辑:这是我的最终设计,包括修改和删除功能(如果有人好奇的话)!
var test = {
members : [],
modifyMember : function(name, value) {
var index = this.members.indexOf(this.members[name]);
if(index < 0) {
return;
}
this.members[index].value = this.members[name].value = value;
},
addMember : function(name, value) {
if(this.members[name]) {
this.modifyMember(name, value);
return;
}
this.members[name] = {
name : name,
value : value,
toString : function() {
return this.name + " has " + this.value;
},
};
this.members.push(this.members[name]);
},
removeMember : function(name) {
if(!this.members[name]) return;
this.members.splice(this.members.indexOf(this.members[name]), 1);
delete this.members[name];
},
toString : function() {
return this.members.join(" AND ");
}
};
答案 0 :(得分:0)
您已经在使用属性扩展数组。现在,不要忘记填充您的数组。使用Array.push()
:
test.addMember = function(name, value) {
this.members[name] = { name : name, value : value };
this.members.push(this.members[name]);
...
};
答案 1 :(得分:0)
一种方法是:(成员是一个对象)
var test = { members : {} };
test.addMember = function(name, value) {
this.members[name] = { name : name, value : value };
this.members[name].toString = function() {
return this.name + " has a " + this.value; };
};
test.toString = function() {
var arr=[];
for(var i in this.members) {
if (this.members.hasOwnProperty(i)){
arr.push(this.members[i].toString());
}
}
return arr.join(" and ");
};
test.addMember("a", "a value");
test.addMember("b", "b value");
alert(test.toString());
另一种方式(成员是一个数组):
var test = { members : [] };
test.addMember = function(name, value) {
var arr= { name : name, value : value };
arr.toString = function() {
return this.name + " has a " + this.value;
};
this.members.push(arr);
};
test.toString = function() {
return this.members.join(" and ");
};
test.addMember("a", "a value");
test.addMember("b", "b value");
alert(test.toString());