makeshift_theory Posted January 26, 2007 Share Posted January 26, 2007 Well I pondered this for a while and came up with a way to detect if a object is in a array. I would like to see if this code can be optmized due to the fact I haven't gotten that far in my JS studies yet ;D. These functions will allows for you to search for a array needle and array haystack and a string needle and array haystack.[code]function isArray() { if (typeof arguments[0] == 'object') { var criterion = arguments[0].constructor.toString().match(/array/i); return (criterion != null); } return false;}function in_array(needle, haystack){ // This will loop through a haystack to find a needle which is an array var hlen = haystack.length; // length of haystack var nlen = needle.length; // length of needle if(isArray(needle)) { for(var i=0;i <= hlen;i++) { // loop through all element in array for(var z=0;z < nlen;z++) { if(needle[z] == haystack[i]) return true; else return false; } } } else { // Not an array for(var i=0;i <= hlen;i++) { if(needle == haystack[i]) return true; else return false; } }}[/code] Link to comment https://forums.phpfreaks.com/topic/35808-in_array-function/ Share on other sites More sharing options...
fenway Posted January 26, 2007 Share Posted January 26, 2007 I've always simply used:[code]( array && array.length && array[0] ) [/code]for my "isArray" check. Link to comment https://forums.phpfreaks.com/topic/35808-in_array-function/#findComment-169766 Share on other sites More sharing options...
makeshift_theory Posted January 26, 2007 Author Share Posted January 26, 2007 I like that a lot better, although I am having issues with the above code. When I run a test it picks up the first entry but it will not pick up any additional entries in the loop.... Link to comment https://forums.phpfreaks.com/topic/35808-in_array-function/#findComment-169773 Share on other sites More sharing options...
makeshift_theory Posted January 26, 2007 Author Share Posted January 26, 2007 Oh I see, I can't use return false or it will exit the function, once I took that out we're golden. Link to comment https://forums.phpfreaks.com/topic/35808-in_array-function/#findComment-169775 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.