简体   繁体   English

在将数组拼接分配给自身时,Javascript控制台打印无法正常工作

[英]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. 大小显示正确,但“a”消失了,我最后得到一个未定义的。

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". 不仅大小减少了2,它还删除了除“a”之外的所有内容。 What is going on? 到底是怎么回事?

Dont assign testArray to itself. 不要将testArray分配给自己。 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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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