程式碼示例:
//indexOf() 方法可返回某個指定的字串值在字串中首次出現的位置。
//利用indexOf()函式統計陣列arr["a","b","d","d","c","d","d"]中元素d出現的次數,
//並同時返回其對應的所有索引下標
var arr=new Array("a","b","d","d","c","d","d");
var numarr = new Array();
var indexnum=0,num;
for (var i=0;i<arr.length;i++) {
num = arr.indexOf("d",0); //獲得第一個d的下表
if(num!=-1){ //記錄個數
numarr[indexnum]=num;
indexnum++;
}
arr[num]="c";
document.write("元素d出現的次數"+indexnum+"<br />");
document.write("所有索引下標:")
for(var i=0;i<numarr.length;i++){
document.write(numarr[i]+",");
程式碼示例:
//indexOf() 方法可返回某個指定的字串值在字串中首次出現的位置。
//利用indexOf()函式統計陣列arr["a","b","d","d","c","d","d"]中元素d出現的次數,
//並同時返回其對應的所有索引下標
var arr=new Array("a","b","d","d","c","d","d");
var numarr = new Array();
var indexnum=0,num;
for (var i=0;i<arr.length;i++) {
num = arr.indexOf("d",0); //獲得第一個d的下表
if(num!=-1){ //記錄個數
numarr[indexnum]=num;
indexnum++;
}
arr[num]="c";
}
document.write("元素d出現的次數"+indexnum+"<br />");
document.write("所有索引下標:")
for(var i=0;i<numarr.length;i++){
document.write(numarr[i]+",");
}