简体   繁体   中英

Javascript console printing not working when assigning splice of array to itself

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?

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM