Crossarrowser inArray function (without jQuery)

I did not know about poor compatibility with the array.indexOf() . But now that I am, I need to find a way to achieve the same, but without using the previous method.

I searched the search engine for a long time, but did not find real convincing answers. At the moment, I am doing this with loops (but this is slower, and I'm sure there are better ways)

Side notes:

  • I can not use jQuery or any other libraries / frameworks.
  • It is not necessary to return an index (just true / false will be fine)

I thought it’s not necessary to share my code, as you all know what loop cycle checking looks like (plus it will lower your IQ).

+6
source share
3 answers

This is how inArray is implemented in jQuery:

 function inArray(elem, array, i) { var len; if ( array ) { if ( array.indexOf ) { return array.indexOf.call( array, elem, i ); } len = array.length; i = i ? i < 0 ? Math.max( 0, len + i ) : i : 0; for ( ; i < len; i++ ) { // Skip accessing in sparse arrays if ( i in array && array[ i ] === elem ) { return i; } } } return -1; } 

You cannot use jQuery, but why not use their implementation ?:-)

Respectfully!

+6
source

From MDN :

 if (!Array.prototype.indexOf) { Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) { "use strict"; if (this == null) { throw new TypeError(); } var t = Object(this); var len = t.length >>> 0; if (len === 0) { return -1; } var n = 0; if (arguments.length > 0) { n = Number(arguments[1]); if (n != n) { // shortcut for verifying if it NaN n = 0; } else if (n != 0 && n != Infinity && n != -Infinity) { n = (n > 0 || -1) * Math.floor(Math.abs(n)); } } if (n >= len) { return -1; } var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0); for (; k < len; k++) { if (k in t && t[k] === searchElement) { return k; } } return -1; } } 

This checks if he sees the inline implementation, if he does not.

Notable Quirks:

t.length >>> 0; is an unsigned shift for strength so that is a positive number

+2
source

I am currently doing this with loops (but this is slow and I'm sure there are better ways)

No matter what you do, cycles will be activated at the end of the day. Unless you come up with an O (1) algorithm for searching inside an array. There is nothing wrong with using a loop to find the corresponding element. You can even extend the inline array object with this method so that it can be reused.

+1
source

Source: https://habr.com/ru/post/905942/


All Articles