0

I'm having an issue with how my arguments are being passed to a new recursion level. Here's a simplified version of what I'm doing:

var newFunction = function(obj) {
  var result = "";
  var args = [];
  Array.prototype.push.apply(args, arguments);
  var thisArg = args.shift()
  //do stuff to add onto result with thisArg. This block works, so I'm skipping.
  if (args.length !== 0) {
    result += newFunction(args);
  };
  return result;
};

The issue I'm having is related to how 'args' is getting passed into newFunction to cycle back through. When the recursive callback is made, args is passed into the new function scope as a single array argument:

  • original arguments = ("string", true, 9, "string 2")
  • new arguments in recursion = ([true, 9, string 2])

It NEEDS to be:

  • original arguments = ("string", true, 9, "string 2")

  • new arguments in recursion = (true, 9, "string 2")

I'm pretty sure it's related to how I'm using .apply for the args variable. I'm just not sure how to get around that, since you can't .shift() the 'arguments' object. The way I'm doing it is setting args to be an array; so when it gets passed in, it is passing it as a single array. This is the problem with my code...

Do you see what I'm doing wrong? Thanks in advance.

3
  • your passing a array into it so of course a array will be present in NewFunction Commented May 28, 2015 at 18:22
  • Right. I'm not sure how to get around that... I'll edit my question to be more clear. Commented May 28, 2015 at 18:23
  • @pointy solved that.. posted it before i could. Commented May 28, 2015 at 18:24

2 Answers 2

2

You can use .apply():

result += newFunction.apply(undefined, args);

The .apply() function is like .call, but it expands the array elements out so that (effectively) the array is copied, element by element, into the arguments object in the newly-called function.

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

1 Comment

Ahhhh, ok. That makes sense. It's going to take me a bit to try that out in my actual code. I'll come back and mark this as solved if (when) it works! Thank you!
1

In ECMAScript 5, using apply:

var newFunction = function(thisArg) {
  var result = "",
      args = [].slice.call(arguments, 1);
  // ...
  if (args.length) result += newFunction.apply(void 0, args);
  return result;
};

In ECMAScript 6, using rest parameters and the spread operator,

var newFunction = function(thisArg, ...args) {
  var result = "";
  // ...
  if (args.length) result += newFunction(...args);
  return result;
};

Comments

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.