Home  >  Article  >  Web Front-end  >  Quickly find an element in an array and return the subscript example_javascript skills

Quickly find an element in an array and return the subscript example_javascript skills

WBOY
WBOYOriginal
2016-05-16 17:23:412871browse
Copy code The code is as follows:

//General implementation one:
function isHasElementOne(arr,value ){
for(var i = 0,vlen = arr.length; i < vlen; i ){
if(arr[i] == value){
return i;
}
}
return -1;
}
//Implementation 2:
function isHasElementTwo(arr,value){
var str = arr.toString();
var index = str.indexOf(value);
if(index >= 0){
//There is a return index
var reg1 = new RegExp("((^|,)" value "(, |$))","gi");
return str.replace(reg1,"$2@$3").replace(/[^,@]/g,"").indexOf("@");
}else{
return -1;//This item does not exist
}
}

Supplementary:
Copy code The code is as follows:

function isHasElement(arr,value){
var str = arr.toString();
var index = str.indexOf(value);
if(index >= 0){
//Return index exists
//"(^" value ",)|(," value ",) |(," value "$)"
value = value.toString().replace(/([|])/g,"\$1");
var reg1 = new RegExp("((^ |,)" value "(,|$))","gi");
return str.replace(reg1,"$2@$3").replace(/[^,@]/g,"") .indexOf("@");
}else{
return -1;//This item does not exist
}
}

Recently writing jquery combobox I encountered efficiency issues when plugging in, and coupled with the class selection of the jquery selector, the efficiency was very slow. After adopting the second method, the efficiency is obviously improved.
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