1

Well, I have to create an object that represents an polynom af any size:

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

what I want to do is write a method that return an array with all these arguments. I read a little about this.arguments, so I write something like that:

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());

and I get this message

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

I'm new at javascript so sorry if there's something wrong, but I would appreciate some help to write this method.

8
  • this.getArguments = ...! Commented Nov 30, 2017 at 2:37
  • const p1 = new polynom(3,2); ... your polynom object does nothing with it's arguments, so, they're lost Commented Nov 30, 2017 at 2:38
  • you just write "this" before all the function? I did this but still the same error Commented Nov 30, 2017 at 2:39
  • A simpler way to get function arguments as an array: [].prototype.slice.call(arguments); Commented Nov 30, 2017 at 2:40
  • @JaromandaX you know how can I fix it? Commented Nov 30, 2017 at 2:42

1 Answer 1

1

What you are looking for is Rest arguments.

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());

Sign up to request clarification or add additional context in comments.

7 Comments

You don't need the loop. The args is already an Array. Just return it, or .slice() it if you want a shallow copy.
... isn't available in all browsers (I'm calling you out, Internet Exploder)
But @rockstar is right, args is already an array, thank you too man.
if you're going to use ES2016+ ... use all of it class polynom { constructor(...args) { this.args = args; } getArguments() { return this.args; } };
for Internet Exploder - function polynom() { this.args = [].slice.call(arguments); } polynom.prototype.getArguments = function() { return this.args; }; - this is all JavaScript 101 stuff!
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.