Jump to content

In_array function


makeshift_theory

Recommended Posts

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
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.