Re: Best way to find if item is in array?
Available news archives: comp.lang.tcl - comp.lang.python - comp.security.firewalls - sci.crypt - comp.lang.php - comp.lang.javascript
Google
 
Web news.hping.org


comp.lang.javascript archive

Re: Best way to find if item is in array?

From: ASM <stephanemoriaux.NoAdmin@wanadoo.fr.invalid>
Date: Wed Aug 31 2005 - 17:36:42 CEST

J. B. Moreno wrote:
> ASM <stephanemoriaux.NoAdmin@wanadoo.fr.invalid> wrote:
>
>>don't know if is better ?
>>
>>alert(myArray.join.indexOf(myValue));

error ! have had to read :

    alert(myArray.join().indexOf(myValue));

> I think I understand that, but let me test my understanding:
> It joins the array into a string, and then searches inside the string
> for the given value? So, if for instance I had myArray = new
> Array("frank", "jim'n'jane"); and did
> alert(myArray.join.indexOf("jane")); it would find it?

no

if it finds it returns '1'
if not it returns '-1'

so for true/false :

   alert(myArray.join().indexOf(myValue)>=0)

that's to say :

   if(myArray.join().indexOf(myValue)>=0) alert('true');
   else alert('false');

> That's not actually a show stopper in this case...but I might have to do
> some test to see if it's actually faster.

a demo ?

<html>
<script type="text/javascript">

tbl = new Array("frank", "jim'n'jane", "moriaux", "toto", "foo");
arr = new Array('potato','salade','pear','orange','apple',banana');

alert(tbl.join().indexOf('ri')>=0);
alert(tbl.join().indexOf('st')>=0);
alert('results must have been :\n true\nfalse');

function verif(myArray,myValue) {
   var yesno = eval(myArray).join().indexOf(myValue)>=0;
   return yesno;
   }

document.write('array = "tbl"<br>content = '+tbl.join()+
'<br>array = arr<br>'+arr.join());
</script>
<form onsubmit="alert(verif(I1.value,I2.value));return false;">
<p>Enter array's name : <input name="I1" value="tbl">
Enter search value : <input name="I2" value="">
<hr><p align=center><input type=submit value="verify">
<input type=reset value="reset">
</form>
</html>

-- 
Stephane Moriaux et son [moins] vieux Mac
Received on Tue Oct 18 03:15:15 2005