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

JavaScript finds and returns specific elements and indexes in an array

巴扎黑
Release: 2017-08-17 13:52:55
Original
4129 people have browsed it
Preface
This article mainly introduces you to the relevant information about using js to find the specified element in the array and return all the indexes of the element. The article gives detailed sample code, as follows Without further ado, let’s take a look at the detailed code examples.
Sample code
//在数组中查找所有出现的x,并返回一个包含匹配索引的数组
function findall(a,x){
 var results=[],
   len=a.length,
   pos=0;
 while(pos<len){
  pos=a.indexOf(x,pos);
  if(pos===-1){//未找到就退出循环完成搜索
   break;
  }
  results.push(pos);//找到就存储索引
  pos+=1;//并从下个位置开始搜索
 }
 return results;
}
  
var arr=[1,2,3,1,4,1,4,1];
findall(arr,1);//返回[0,3,5,7]
Copy after login

The above is the detailed content of JavaScript finds and returns specific elements and indexes in an array. For more information, please follow other related articles on the PHP Chinese website!

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!