javascript模拟php函数in_array

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

javascript模拟php函数in_array

  2020-05-13 我要评论

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

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

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

jQuery中有类似的函数:http:/https://img.qb5200.com/download-x/docs.jquery.com/Utilities/jQuery.inArray

它的代码如下:

function inArray(needle, haystack) {
  var length = haystack.length;
  for(var i = 0; i < length; i++) {
    if(haystack[i] == needle) return true;
  }
  return false;
}

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

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们