Javascript“移位”与“拼接” - 这些语句是否相等?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10742369/
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-10-26 10:53:03  来源:igfitidea点击:

Javascript "shift" versus "splice" - are these statements equal?

javascriptarraysarray-splice

提问by J. Bruni

I just want to confirm if the following two Javascript statements produces the same results, as it seems to me:

我只想确认以下两个 Javascript 语句是否产生相同的结果,在我看来:

First:

第一的:

var element = my_array.splice(0,1)[0];

Second:

第二:

var element = my_array.shift();

I want to substitute the first by the second, in my own code, to improve readability. Can I do this?

我想在我自己的代码中用第二个替换第一个,以提高可读性。我可以这样做吗?

回答by James Allardice

They will have the same effect, yes. splice(0, 1)will remove the first element from my_arrayand return a new array containing that element. shiftwill do the same, but return the element itself, not an array.

它们会产生相同的效果,是的。splice(0, 1)将从中删除第一个元素my_array并返回一个包含该元素的新数组。shift会做同样的事情,但返回元素本身,而不是数组。

shiftis more readable (in my opinion) and is also significantly faster(in Chrome at least):

shift更具可读性(在我看来)并且速度明显更快(至少在 Chrome 中):

enter image description here

在此处输入图片说明

回答by Maxim Krizhanovsky

Both lines of code remove the first element from the array, and return the removed element, they are both supported in all major browsers.

两行代码都从数组中删除第一个元素,并返回删除的元素,所有主要浏览器都支持它们。

You should use the second one, and the code will be more readable indeed.

您应该使用第二个,并且代码确实会更具可读性。

回答by jbabey

shiftreturns the element that was removed, splicereturns an array of elements that were removed.

shift返回被删除的元素,splice返回被删除的元素数组。

that being said, the two statements do the same thing and i would agree that the second is more readable.

话虽如此,这两个陈述做同样的事情,我同意第二个更具可读性。