有没有理由JavaScript开发人员不使用Array.push()? [英] Is there a reason JavaScript developers don't use Array.push()?

查看:74
本文介绍了有没有理由JavaScript开发人员不使用Array.push()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我经常看到开发人员在JavaScript中使用如下表达式:

I commonly see developers use an expression like the following in JavaScript:

arr = []
arr[arr.length] = "Something"
arr[arr.length] = "Another thing"

不会推送更合适吗?

arr = []
arr.push("Something")
arr.push("Another thing")


推荐答案

我实际上在今年年初问自己同样的问题。 更新了新的测试用例 http:/ /jsperf.com/array-push-vs-unshift-vs-direct-assignment/2

I actually asked myself the same question at the start of this year. UPDATED with new test cases http://jsperf.com/array-push-vs-unshift-vs-direct-assignment/2

似乎 push 在chrome中快得多,在FF中大约相等。在IE9中直接也更快,但我很想知道它在IE10中的表现。

It appears that push is much faster in chrome, and about equal in FF. Also direct is faster in IE9, but I would be interested to see how it performs in IE10.

我想说大多数开发人员会假设设置数组的长度,然后使用直接赋值更快,就像大多数编程语言一样。但JavaScript是不同的。 Javascript数组不是真正的数组,它们只是关键/ value映射就像所有其他JavaScript对象一样。所以预分配基本上是充耳不闻。

I would say that most developers would assume setting the length of the array, and then using direct assignment is faster, as is the case with most programming languages. But JavaScript is different. Javascript arrays aren't really arrays, they're just key/value maps just like all other JavaScript objects. So the pre-allocation is essentially falling on deaf ears.

我个人更喜欢推送(:

这篇关于有没有理由JavaScript开发人员不使用Array.push()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆