[英]javascript array splice without index
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? 从这里开始 ,结果是
[0, 1, 2, -3, -4, -5, -6, 7, 8, 9]
,任何人都能解释一下这个吗?
function .apply(context, argsArray) calls function in the given context, passing argsArray as the arguments for function . function .apply(context,argsArray)在给定的上下文中调用函数 ,传递argsArray作为函数的参数。
In this case, function is [].splice
, which takes the following parameters, in this this order: 在这种情况下, 函数是
[].splice
,它按以下顺序获取以下参数:
[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]
. [3,4].concat(_ref = [-3, -4, -5, -6])
通过将两个数组连接在一起来计算数组,给出[3, 4, -3, -4, -5, -6]
。 This is the argsArray passed to .apply()
, so that: 这是传递给
.apply()
,因此:
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. 因此
.apply()
导致.splice()
函数在numbers
数组的上下文中运行,删除索引3,4,5和6处的元素,然后插入元素-3,-4,-5和 -原始数组中的“2”和“7”之间的比较。
Edit: See RobG's answer for a summary of what the original code is equivalent to (rather than an explanation of its parts). 编辑:请参阅RobG的答案,了解原始代码等同的内容(而不是对其部分的解释)。
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.参见拼接 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.