我想将几个变量写入一个数组,以便一次调用" addLetter"方法,"推"和#34; concat"不起作用
function Team(name) {
this.name = name;
this.letters = [];
}
Team.prototype.addLetter = function (letter) {
this.letters.push(letter).join('\n');
};
Team.prototype.toString = function () {
return "Name of team - " + this.name + '\n' +"ltters : " + this.letters;
};
var a = 's';
b='g';
v='d';
var team1 = new Team('letters');
team1.addLetter(a,b,v);
console.log(team1.toString());

答案 0 :(得分:1)
如果你正在使用ES6:
Team.prototype.addLetter = function() {
this.letters.push(...arguments);
};
使用较旧的语法:
Team.prototype.addLetter = function() {
this.letters.push.apply(this.letters.push, arguments);
};
JavaScript允许将任意数量的参数传递给任何函数。所有这些参数都可以通过函数中的arguments
变量访问,该变量是一个类似于数组的对象,包含所有参数的传递顺序。