将数组拼接分配给自身时,Javascript 控制台打印不起作用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12321210/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 07:43:28  来源:igfitidea点击:

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

javascriptarrays

提问by Dragonfly

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". What is going on?

大小不仅减少了 2,而且删除了除“a”之外的所有内容。到底是怎么回事?

回答by James Kleeh

Dont assign testArray to itself. Simply do:

不要将 testArray 分配给自身。简单地做:

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