Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery: array zero vs function get zero: [0] vs get(0)

Tags:

jquery

Is there any reason I should use $('#x>div').get(1) when I could instead just use $('#x>div')[1]? Is there a difference?

like image 963
700 Software Avatar asked Feb 12 '11 01:02

700 Software


2 Answers

Nope, no difference. jQuery holds all DOM nodes in an Array.

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

--jQuery source snippet--

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

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

As you can see, .get() with no arguments will return all nodes as Array. This cannot be accomplished with brackets.

like image 153
jAndy Avatar answered Oct 23 '22 07:10

jAndy


No, and performance is about the same because the creation of a jQuery object dominates array/function access time:

Browser      get Ops/sec  array Ops/sec  #tests
Chrome 9     20,555       22,671         2
like image 29
atp Avatar answered Oct 23 '22 07:10

atp