0

I'm trying to change function arguments inside another function and then returns it to callee function. I'm trying something like this:

function func(a,b,c) {
    console.log(arguments, a, b, c); //[1, true, "a"] 1 true "a"
  arguments[0] = 2;
    console.log(arguments, a, b, c); //[2, true, "a"] 2 true "a"
  arguments = ArgumentsToNumber.apply(this, arguments);
  console.log(arguments, a, b, c); //[2, 1, NaN] 2 true "a"
}

function ArgumentsToNumber() {
    for (let i = 0; i < arguments.length; i++) {
    arguments[i] = Number(arguments[i]);
  }
  return arguments;
}

func(1, true, 'a');

I want changes in a, b and c variables.

4
  • Why not just use array.map in func? arguments = arguments.map((argument) => Number(argument)) Commented Apr 3, 2016 at 18:26
  • 1
    @AkshatMahajan That will thrown an error. arguments is not an array Commented Apr 3, 2016 at 18:27
  • This doesn't look like good practice arguments[0] = 2. You probably want to convert the arguments to an array first. [].slice.call(arguments) or map over them in some way like [].map.call(arguments, callback) Commented Apr 3, 2016 at 18:27
  • You must borrow map from array e.g. [].map.call(arguments, Number) Commented Apr 3, 2016 at 18:27

1 Answer 1

1

You must pass the Arguments object itself, instead of using it as an array-like in apply:

function func(a, b, c) {
  console.log(a, b, c); // 1, true, "a"
  arguments[0] = 2;
  console.log(a, b, c); // 2, true, "a"
  argumentsToNumber(arguments);
  console.log(a, b, c); // 2,    1, NaN
}
function argumentsToNumber(args) {
  for (let i = 0; i < args.length; i++)
    args[i] = +args[i];
}
func(1, true, 'a');

Note that changing the arguments in another function has bad performance.

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

2 Comments

@HenriCavalcante See for example jspatterns.com/arguments-considered-harmful
it's arguments.callee or passing the whole arguments object that slows things down, but even those don't slow down code very much. 3site.eu/jstests/arguments.callee.calls.html?times=50000

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.