如何在javascript中创建具有未知数量参数的对象?

时间:2017-11-30 02:35:22

标签: javascript

好吧,我必须创建一个表示任何大小的多项式的对象:

var polynom = function() {
    //code ...
};
p1 = polynom(1,6,3,4); // 1x^6 + 3x^4
p2 = polynom(3,5,2,1,7,3); // 3x^5 + 2x^1 + 7x^3

我想要做的是编写一个返回包含所有这些参数的数组的方法。我读了一些关于this.arguments的内容,所以我写了类似的东西:

var polynom = function() {

    getArguments = function() {
    array = [];
    for(var i = 0; i < this.arguments.size; i++) array.push(this.arguments[i]);
    return array;
  }
};

const p1 = new polynom(3,2);
console.log(p1.getArguments());

我收到此消息

TypeError: Cannot read property 'getArguments' of undefined
    at eval:14:16
    at eval
    at new Promise

我是javascript的新手很抱歉,如果出现问题,我会很感激帮助我们编写这种方法。

1 个答案:

答案 0 :(得分:1)

您要找的是Rest arguments

&#13;
&#13;
var polynom = function(...args) {
  this.getArguments = function() {
    var array = [];
    for(var i = 0; i < args.length; i++) {array.push(args[i]);};
    return array;
  }
};

const p1 = new polynom(3,2);
console.log(p1.getArguments());
&#13;
&#13;
&#13;