[英]Funny behaviour of Array.splice()
I was experimenting with the splice() method in jconsole 我正在jconsole中使用splice()方法进行实验
a = [1,2,3,4,5,6,7,8,9,10]
1,2,3,4,5,6,7,8,9,10
Here, a is a simple array from 1 to 10. 在这里,a是一个从1到10的简单数组。
b = ['a','b','c']
a,b,c
And this is b 这是b
a.splice(0, 2, b)
1,2
a
a,b,c,3,4,5,6,7,8,9,10
When I pass the array b to the third argument of splice, I mean "remove the first two arguments of a from index zero, and replace them with the b array". 当我将数组b传递给splice的第三个参数时,我的意思是“从索引0中删除a的前两个参数,并将其替换为b数组”。 I've never seen passing an array as splice()'s third argument (all the guide pages I read talk about a list of arguments), but, well, it seems to do the trick.
我从未见过将数组作为splice()的第三个参数传递( 我阅读的所有指南页都讨论了参数列表),但是,这似乎可以解决问题。 [1,2] are removed and now a is [a,b,c,3,4,5,6,7,8,9,10].
[1,2]被删除,现在a为[a,b,c,3,4,5,6,7,8,9,10]。 Then I build another array, which I call c:
然后,我建立另一个数组,我称之为c:
c = ['one','two','three']
one,two,three
And try to do the same: 并尝试执行相同的操作:
a.splice(0, 2, c)
a,b,c,3
a
one,two,three,4,5,6,7,8,9,10
This time, 4 (instead of 2) elements are removed [a,b,c,3] and the c array is added at the beginning. 这次,删除了4个(而不是2个)元素[a,b,c,3],并在开头添加了c数组。 Someone knows why?
有人知道为什么吗? I'm sure the solution is trivial, but I don't get it right now.
我敢肯定解决方案是微不足道的,但我现在不明白。
Array.splice
does not support an array as the third parameter. Array.splice
不支持的阵列作为第三个参数。
Reference: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/splice 参考: https : //developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/splice
Using Firebug (or Chrome's Console), one sees what really happens: 使用Firebug (或Chrome的控制台),可以看到实际发生的情况:
a.splice(0, 2, b)
> [1, 2]
a
> [["a", "b", "c"], 3, 4, 5, 6, 7, 8, 9, 10]
Problem here is jconsole, which just uses toString()
to print out the arrays, but Array.toString()
does not print any []
. 这里的问题是jconsole,它仅使用
toString()
打印出数组,但是Array.toString()
不打印任何[]
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.