Array.splice() 的有趣行为

发布于 2024-10-06 03:22:28 字数 859 浏览 5 评论 0原文

我正在 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

将军与妓 2024-10-13 03:22:28

Array.splice 支持数组作为第三个参数。
参考:https://developer.mozilla.org/en/JavaScript/Reference /Global_Objects/Array/splice

使用 Firebug (或 Chrome 的控制台),可以看到到底发生了什么:

a.splice(0, 2, b)
> [1, 2]
a
> [["a", "b", "c"], 3, 4, 5, 6, 7, 8, 9, 10]

问题在这里是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:

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 [].

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文