Array.splice() 的有趣行为
我正在 jconsole 中尝试 splice() 方法,
a = [1,2,3,4,5,6,7,8,9,10]
1,2,3,4,5,6,7,8,9,10
这里,a 是一个从 1 到 10 的简单数组。
b = ['a','b','c']
a,b,c
这是b
a.splice(0, 2, b)
1,2
a
a,b,c,3,4,5,6,7,8,9,10
当我将数组 b 传递给 splice 的第三个参数时,我的意思是“从索引零中删除 a 的前两个参数,并将它们替换为 b 数组”。我从未见过将数组作为 splice() 的第三个参数传递(我读过的所有 指南页面 谈论参数列表),但是,好吧,它似乎可以解决问题。 [1,2] 被删除,现在 a 是 [a,b,c,3,4,5,6,7,8,9,10]。然后我构建另一个数组,我将其称为 c:
c = ['one','two','three']
one,two,three
并尝试执行相同操作:
a.splice(0, 2, c)
a,b,c,3
a
one,two,three,4,5,6,7,8,9,10
这一次,删除了 4 个(而不是 2 个)元素 [a,b,c,3] 并在开头添加了 c 数组。有人知道为什么吗?我确信解决方案很简单,但我现在不明白。
I was experimenting with the splice() method in jconsole
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.
b = ['a','b','c']
a,b,c
And this is 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". 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. [1,2] are removed and now a is [a,b,c,3,4,5,6,7,8,9,10]. Then I build another array, which I call 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. Someone knows why? I'm sure the solution is trivial, but I don't get it right now.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
Array.splice
不支持数组作为第三个参数。参考:https://developer.mozilla.org/en/JavaScript/Reference /Global_Objects/Array/splice
使用 Firebug (或 Chrome 的控制台),可以看到到底发生了什么:
问题在这里是jconsole,它只使用
toString()
打印出数组,但Array.toString()
不打印任何[]
。Array.splice
does not support an array as the third parameter.Reference: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/splice
Using Firebug (or Chrome's Console), one sees what really happens:
Problem here is jconsole, which just uses
toString()
to print out the arrays, butArray.toString()
does not print any[]
.