欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

javascript模擬php函數(shù)in_array

 更新時(shí)間:2015年04月27日 15:11:02   投稿:hebedich  
就是判斷一個(gè)元素是否存在于數(shù)組中的函數(shù),既然js里string都有indexOf函數(shù),為什么不在Array對象里設(shè)置一個(gè)這樣的函數(shù)呢,其實(shí)就用indexOf這個(gè)思想挺好的,不知道制定JS標(biāo)準(zhǔn)的人是基于什么考慮,把這樣一個(gè)如此常用的功能沒考慮在內(nèi)的。

js 中判斷某個(gè)元素是否存在于某個(gè) js 數(shù)組中,相當(dāng)于 php 語言中的 in_array 函數(shù)。

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 數(shù)組中,存在返回true 否則false,此處將返回true 

注:此函數(shù)只對字符和數(shù)字有效

jQuery中有類似的函數(shù):http://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;
}

以上就是本文給大家分享的全部內(nèi)容了,希望大家能夠喜歡。

相關(guān)文章

最新評論