您现在的位置: 万盛学电脑网 >> 程序编程 >> 脚本专题 >> javascript >> 正文

javascript模拟php函数in

作者:佚名    责任编辑:admin    更新时间:2022-06-22

   就是判断一个元素是否存在于数组中的函数,既然js里string都有indexOf函数,为什么不在Array对象里设置一个这样的函数呢,其实就用indexOf这个思想挺好的,不知道制定JS标准的人是基于什么考虑,把这样一个如此常用的功能没考虑在内的。

  js 中判断某个元素是否存在于某个 js 数组中,相当于 php 语言中的 in_array 函数。

  ?

1 2 3 4 5 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)); };

  用法如下:

  ?

1 2 var arr=new Array(["b",2,"a",4,"test"]); arr.in_array('test');//判断 test 字符串是否存在于 arr 数组中,存在返回true 否则false,此处将返回true

  注:此函数只对字符和数字有效

  jQuery中有类似的函数:http://docs.jquery.com/Utilities/jQuery.inArray

  它的代码如下:

  ?

1 2 3 4 5 6 7 function inArray(needle, haystack) { var length = haystack.length; for(var i = 0; i < length; i++) { if(haystack[i] == needle) return true; } return false; }

  以上就是本文给大家分享的全部内容了,希望大家能够喜欢。