要判断数组中是否包含某个元素,从原理来来说,就是遍历整个数组,然后判断是否相等,我们来造个轮子,名字就山寨PHP的数组函数in_array()
- Array.prototype.in_array = function(e)
- {
- for (i= 0 ;i< this .length;i++)
- {
- if ( this [i] == e)
- return true ;
- }
- return false ;
- }
Array.prototype.in_array = function(e)
{
for(i=0;i<this.length;i++)
{
if(this[i] == e)
return true;
}
return false;
}
或者
- Array.prototype.in_array = function(e)
- {
- for (i= 0 ;i< this .length && this [i]!=e;i++);
- return !(i== this .length);
- }
Array.prototype.in_array = function(e)
{
for(i=0;i<this.length && this[i]!=e;i++);
return !(i==this.length);
}
这两个都是可以的。其实就是一个形式,写法不一样而已。 还有一个大牛是这样写的
- Array.prototype.S=String.fromCharCode( 2 );
- Array.prototype.in_array=function(e)
- {
- var r=new RegExp( this .S+e+ this .S);
- return (r.test( this .S+ this .join( this .S)+ this .S));
- }
Array.prototype.S=String.fromCharCode(2);
Array.prototype.in_array=function(e)
{
var r=new RegExp(this.S+e+this.S);
return (r.test(this.S+this.join(this.S)+this.S));
}
使用方法就是
- var arr=[ "a" , "b" ];
- alert(arr.in_array("a" ))
var arr=["a","b"];
alert(arr.in_array("a"))