English 中文(简体)
Funny behaviour of Array.splice()
原标题:

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.

最佳回答

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

问题回答

暂无回答




相关问题
selected text in iframe

How to get a selected text inside a iframe. I my page i m having a iframe which is editable true. So how can i get the selected text in that iframe.

How to fire event handlers on the link using javascript

I would like to click a link in my page using javascript. I would like to Fire event handlers on the link without navigating. How can this be done? This has to work both in firefox and Internet ...

How to Add script codes before the </body> tag ASP.NET

Heres the problem, In Masterpage, the google analytics code were pasted before the end of body tag. In ASPX page, I need to generate a script (google addItem tracker) using codebehind ClientScript ...

Clipboard access using Javascript - sans Flash?

Is there a reliable way to access the client machine s clipboard using Javascript? I continue to run into permissions issues when attempting to do this. How does Google Docs do this? Do they use ...

javascript debugging question

I have a large javascript which I didn t write but I need to use it and I m slowely going trough it trying to figure out what does it do and how, I m using alert to print out what it does but now I ...

Parsing date like twitter

I ve made a little forum and I want parse the date on newest posts like twitter, you know "posted 40 minutes ago ","posted 1 hour ago"... What s the best way ? Thanx.

热门标签