Home  >  Article  >  php教程  >  自定义类似php的js数组的in

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

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

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'));



Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn