jQuery:数组零vs函数得零:[0] vs get(0)

Bry*_*eld 16 jquery

有什么理由我可以使用$('#x>div').get(1),而不是只使用$('#x>div')[1]?有区别吗?

jAn*_*ndy 15

不,没有区别.jQuery将所有DOM节点保存在一个Array中.

$().get(1) === $()[1]

--jQuery源代码段 -

get: function( num ) {
    return num == null ?
        // Return a 'clean' array
        this.toArray() :

        // Return just the object
        ( num < 0 ? this[ this.length + num ] : this[ num ] );
},
Run Code Online (Sandbox Code Playgroud)

如您所见,.get()没有参数会将所有节点作为Array返回.这不能用括号来完成.


atp*_*atp 7

不,并且性能大致相同,因为jQuery对象的创建支配了数组/函数访问时间:

Browser      get Ops/sec  array Ops/sec  #tests
Chrome 9     20,555       22,671         2
Run Code Online (Sandbox Code Playgroud)

  • 在您的测试中,您也进行了相对繁重的操作(创建jQuery对象和DOM选择)这一事实掩盖了您的比较.如果你从测试中删除它们,差异显示是巨大的.http://jsperf.com/get-vs-array/2`array:123,366,553/get:4,062,520`所以@George的期望绝对正确. (9认同)
  • 呵呵..我希望数组方法更有效率,因为你不必经历这个功能. (2认同)
  • 更新:在 Chrome 47 中,[性能](http://jsperf.com/get-vs-array/2) 差异变得明显更小:`array: 397,779,318 / get: 343,623,455`(这是我的本地结果 - 失败加载其他结果) (2认同)