Heim  >  Artikel  >  php教程  >  自定义类似php的js数组的in

自定义类似php的js数组的in

WBOY
WBOYOriginal
2016-06-06 19:54:00974Durchsuche

PHP的数组函数in_array()非常方便,可JS就不是了。其实我很不喜欢JS的数组~ 别说了,直接上方法 Array.prototype.in_array=function(e) { for(i=0;ithis.length;i) { if(this[i]==e) returntrue; } returnfalse; } 或者 Array.prototype.in_array=function(e

PHP的数组函数in_array()非常方便,可JS就不是了。其实我很不喜欢JS的数组~

别说了,直接上方法

Array.prototype.in_array = function(e) 

    for(i=0;i     {
        if(this[i] == e)
        return true;
    }
    return false;
}

或者

Array.prototype.in_array = function(e) 

for(i=0;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));
}

我个人比较喜欢这个,看不懂么有关系,你只管用我写好的代码就成了,嘎嘎。。

模拟数据检测一下就好

var aa = new Array(1,2,'aa','bbb',4,5); 
alert(aa.in_array(3)); 
alert(aa.in_array('aa'));



Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn