0

I was wondering about this piece of code:

var numbers, _ref;
numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];

[].splice.apply(numbers, [3, 4].concat(_ref = [-3, -4, -5, -6])), _ref;
alert(numbers);

From here, the result is [0, 1, 2, -3, -4, -5, -6, 7, 8, 9] and can anyone explain me about this?

3 Answers 3

1

function.apply(context, argsArray) calls function in the given context, passing argsArray as the arguments for function.

In this case, function is [].splice, which takes the following parameters, in this this order:

  1. index - at which to start changing the array
  2. howMany - elements to remove, starting at index
  3. element1,...,elementN - elements to insert into the array at index

[3,4].concat(_ref = [-3, -4, -5, -6]) evaluates to an array by concatenating the two arrays together, giving [3, 4, -3, -4, -5, -6]. This is the argsArray passed to .apply(), so that:

  1. index == 3 (start at index 3)
  2. howMany == 4 (remove 4 elements)
  3. element1,...,elementN == -3, -4, -5, -6 (the elements to insert at index 3, after removal)

Thus .apply() is causing the .splice() function to run in the context of the numbers array, removing elements at indices 3, 4, 5 and 6, and then inserting the elements -3, -4, -5 and -6 between "2" and "7" in the original array.

Edit: See RobG's answer for a summary of what the original code is equivalent to (rather than an explanation of its parts).

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

2 Comments

Whoever gave that -1, care to explain why?
If what you are looking for is an easy to use function that does this check out insertArrayAt() in this answer stackoverflow.com/a/12189963/984780
1

Your code resolves to the following variable declarations:

var numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
var _ref = [-3, -4, -5, -6];

And these expressions:

numbers.splice(3, 4, -3, -4, -5, -6);
_ref;
alert(numbers);

Comments

0

[3, 4].concat(_ref = [-3, -4, -5, -6]) evals to [3, 4, -3, -4, -5, -6] and [].splice.apply(numbers, [3, 4, -3, -4, -5, -6])) to numbers.splice(3, 4, -3, -4, -5, -6) causing 4 elements stating from index 3 to be removed and the elements "-3, -4, -5, -6" to be inserted at the index 3. See splice.

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.