Home > Web Front-end > JS Tutorial > body text

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

WBOY
Release: 2016-05-16 17:23:41
Original
2876 people have browsed it
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.
Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!