1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <meta http-equiv="X-UA-Compatible" content="IE=edge"> 6 <meta name="viewport" content="width=device-width, initial-scale=1.0"> 7 <title>利用indexof()函数统计数组中的元素,并返回小标</title> 8 </head> 9 <body> 10 11 </body> 12 <script> 13 var arr = ['a','b','d','d','c','d','d'];//查找元素所在的数组 14 var brr = [];//存储下标的空数组 15 var search = 'd';//要查找的元素 16 var sum = 0;//arr数组中元素出现次数统计 17 var a = b = 0; 18 if(arr.indexOf(search) === -1){//查找的元素不存在 19 document.write("元素"+search+"不存在"); 20 }else if(arr.indexOf(search) > -1){//防止返回的下标为0,if判断为false 21 for (var i = 0;i < arr.length;i++) {//遍历数组arr 22 a = arr.indexOf(search,i);//通过遍历查找search的每一个下标 23 if(brr.indexOf(a) === -1){//判断brr数组是否含有相同的下标 24 brr[b] = a;//将下标存入brr数组中 25 b++; 26 sum++; 27 } 28 } 29 } 30 document.writeln(search+"共出现"+sum+"次。"); 31 for (const i in brr) { 32 document.writeln("下标为:"+brr[i]); 33 } 34 </script> 35 </html>