objects = [{
name: "The Godfather",
year: 1972
}, {
name: "Scarface",
year: 1983
}, {
name: "The Godfather II",
year: 1974
}]; // Apoligies f
alert(objects);
我想这样做,警报返回每部电影的名称,例如为三个电影对象中的每一个定义一个toString
方法。有没有办法在objects
的数组定义中执行此操作,还是必须单独创建每个对象并将其推送到数组?我更喜欢第一种选择,如下所示:
objects = [{
name: "The Godfather",
year: 1972,
toString: function {
return name
}
}, {
name: "Scarface",
year: 1983,
toString: function {
return name
}
}, {
name: "The Godfather II",
year: 1974,
toString: function {
return name
}
}];
alert(objects);
答案 0 :(得分:0)
Oluwafemi的解决方案起到了作用:
objects = [{name:"The Godfather", year:1972, toString:function(){return this.name}},{name:"Scarface", year:1982, toString:function(){return this.name}},{name:"The Godfather II", year:1974, toString:function(){return this.name}}];
答案 1 :(得分:0)
您必须将this.name
添加到toString
功能。
objects = [{
name: "The Godfather",
year: 1972,
toString: function() {
return this.name
}
}, {
name: "Scarface",
year: 1983,
toString: function() {
return this.name
}
}, {
name: "The Godfather II",
year: 1974,
toString: function() {
return this.name
}
}];
alert(objects[1].toString());

答案 2 :(得分:0)
使用function() { return this.name };
更好的是,重复使用相同的功能,而不是每次都创建一个新功能。
function toString() {
return this.name;
}
objects = [
{name:"The Godfather", year:1972, toString: toString}
{name:"Scarface", year:1983, toString: toString},
{name:"The Godfather II", year:1974, toString: toString}
];
alert(objects);
好多了,编写一个包装函数,返回一个附加到对象原型的toString
的新对象。
function Movie(obj) {
this.name = obj.name;
this.year = obj.year;
}
Movie.prototype.toString = function() {
return this.name;
};
objects = [
new Movie({name:"The Godfather", year:1972}),
new Movie({name:"Scarface", year:1983}),
new Movie({name:"The Godfather II", year:1974}),
];
alert(objects);