javascript - Best way to test a series of items -
i'm looking advice simple pattern. is, checking series of things against test. needs work ie8+
normally, simple seems appropriate small tests (i.e. < 3 items):
if (sometest === 'one' || sometest === 'two' || sometest === 'three' ) { // } but lately i've been thinking other ways same thing:
var arrayofsomething= ['one', 'two', 'three', 'four']; var arraylength = arrayofsomething.length; (var = 0; < arraylength; i++) { if ( sometest === arrayofsomething[i]) { // } } the first method seems more readable , requires less code (assuming list small) , doesn't require 2 additional variables. second method more efficient, less redundant more complex , less readable.
am over-thinking this? there optimal method?
ie8 doen't support indexof
to cross browser, use https://api.jquery.com/jquery.inarray/
if ($.inarray(sometest,arrayofsomething) > -1) { // } edit
from jquery source code :
inarray: function( elem, arr, ) { var len; if ( arr ) { if ( indexof ) { return indexof.call( arr, elem, ); } len = arr.length; = ? < 0 ? math.max( 0, len + ) : : 0; ( ; < len; i++ ) { // skip accessing in sparse arrays if ( in arr && arr[ ] === elem ) { return i; } } } return -1; },
Comments
Post a Comment