有什么理由我可以使用$('#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返回.这不能用括号来完成.
不,并且性能大致相同,因为jQuery对象的创建支配了数组/函数访问时间:
Browser get Ops/sec array Ops/sec #tests
Chrome 9 20,555 22,671 2
Run Code Online (Sandbox Code Playgroud)