【发布时间】:2011-02-12 01:32:40
【问题描述】:
如果我可以只使用$('#x>div')[1],我有什么理由应该使用$('#x>div').get(1)?有区别吗?
【问题讨论】:
-
这是一个精确副本,但我没有链接。
-
这就是我拼出这些词的原因。所以以后通过搜索会更容易找到。只是拼出几个单词以防万一。 @pst
标签: jquery
如果我可以只使用$('#x>div')[1],我有什么理由应该使用$('#x>div').get(1)?有区别吗?
【问题讨论】:
标签: jquery
不,没有区别。 jQuery 将所有 DOM 节点保存在一个数组中。
$().get(1) === $()[1]
--jQuery源码sn-p--
get: function( num ) {
return num == null ?
// Return a 'clean' array
this.toArray() :
// Return just the object
( num < 0 ? this[ this.length + num ] : this[ num ] );
},
如您所见,不带参数的.get() 会将所有节点作为数组返回。这不能用括号来完成。
【讨论】:
不,性能是about the same,因为创建 jQuery 对象支配了数组/函数的访问时间:
Browser get Ops/sec array Ops/sec #tests
Chrome 9 20,555 22,671 2
【讨论】:
array: 123,366,553 / get: 4,062,520 所以@George 的预期是绝对正确的。
array: 397,779,318 / get: 343,623,455(这是我的本地结果 - 无法加载其他结果)