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?
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:
[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:
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).
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);
[3, 4].concat(_ref = [-3, -4, -5, -6])
逃避[3, 4, -3, -4, -5, -6]
和[].splice.apply(numbers, [3, 4, -3, -4, -5, -6]))
到numbers.splice(3, 4, -3, -4, -5, -6)
导致4个元素从索引3开始要删除并将元素“-3,-4,-5,-6”插入索引3.参见拼接 。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.