understanding javascripts ( length - 1 ) in obj check to test for isArraylike (jquery) -


i going through source code of jquery , came across following function:

function isarraylike( obj ) {      // support: ios 8.2 (not reproducible in simulator)     // `in` check used prevent jit error (gh-2145)     // hasown isn't used here due false negatives     // regarding nodelist length in ie     var length = "length" in obj && obj.length,         type = jquery.type( obj );      if ( type === "function" || jquery.iswindow( obj ) ) {         return false;     }      if ( obj.nodetype === 1 && length ) {         return true;     }      return type === "array" || length === 0 ||         typeof length === "number" && length > 0 && ( length - 1 ) in obj; } 

if go line line , see jquerys internal methods called such $.type , $.iswindow, part don't understand right @ end, following piece of code:

( length - 1 ) in obj; 

i see && used in end, question when check return true , when return false? hard tell, check when obj object or when obj array?

what check really really checking for?

i created following piece of code, make sense of line:

arr = ['hello' , 'world'];  check = (arr - 1) in arr;  console.log(check); 

well false in console, have no idea scenario return true . can shed light on please?

this simple has nothing jquery. that's javascript. checks if key part of object or array.

var a=["a","b","c","d"] 

has @ least 4 keys 0,1,2 , 3 can positively test keys, i.e. in console

0 in true 1 in true 2 in true 3 in true 4 in false 

so (length-1) in obj checks if last element of array or object defined or not.

that done, define a as

var a={ "0":"a", "3":"d", "length":4 } 

which sparse array.

your test code be

arr = ['hello' , 'world']; check = (arr.length - 1) in arr; console.log(check); 

Comments

Popular posts from this blog

c# - Better 64-bit byte array hash -

webrtc - Which ICE candidate am I using and why? -

php - Zend Framework / Skeleton-Application / Composer install issue -