js 中判斷某個元素是否存在于某個 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)容了,希望大家能夠喜歡。
新聞熱點(diǎn)
疑難解答