Javascript Splice not working correctly

When I do this:

var testArray  = ["a","b","c"];
console.log(testArray);
console.log("size:" + testArray.length);

I this this printed in my console:

["a", "b", "c"]
size:3 

Which is good. But now when I start splicing with this:

var testArray  = ["a","b","c"];
console.log(testArray);
console.log("size:" + testArray.length);
testArray = testArray.splice(0,1);

This happens to show in my console:

["b", "c", undefined × 1]
size:3 

So first question is why does it mess up my printing of the array even though the splice was after the printing? The size is shown correctly but the "a" is gone and I get an undefined at the end.

So what I wanted to do was to remove the first item in the array. Basically a shift. So I do this:

var testArray  = ["a","b","c"];
console.log(testArray);
console.log("size:" + testArray.length);
testArray = testArray.splice(0,1);
console.log(testArray);
console.log("size:" + testArray.length);

And this is what gets outputted:

["b", "c", undefined × 1]
size:3
["a"]
size:1 

Not only did the size decrease by 2, it deleted everything but the "a". What is going on?

Answers


Dont assign testArray to itself. Simply do:

var testArray  = ["a","b","c"];
console.log(testArray);
console.log("size:" + testArray.length);
testArray.splice(0,1);
console.log(testArray);
console.log("size:" + testArray.length);

Need Your Help

How to pass data from CustomMessageBox to the page which called it?

c# windows-phone-8

I have a page where I call one xaml layout page as a CustomMessageBox which displays country list. I am displaying the country list with the help of LongListSelector. After selecting the country , ...

Can I use hyperlinks as a form submit which posts $_GET values instead of making an hyperlink which has $_GET values?

html url hyperlink get form-submit

I am using many get values in one page and making up a hyperlink with adding ?var=value&... each time is time cosuming. I would like to use hyperlinks as a submit button in a form and html would

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.