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
Javascript "shift" versus "splice" - are these statements equal?
提问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_array
and return a new array containing that element. shift
will do the same, but return the element itself, not an array.
它们会产生相同的效果,是的。splice(0, 1)
将从中删除第一个元素my_array
并返回一个包含该元素的新数组。shift
会做同样的事情,但返回元素本身,而不是数组。
shift
is more readable (in my opinion) and is also significantly faster(in Chrome at least):
shift
更具可读性(在我看来)并且速度也明显更快(至少在 Chrome 中):
回答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.
您应该使用第二个,并且代码确实会更具可读性。