Bootstrap

javascript 几句话快速找出字符串内指定字符的下标。

今天在和朋友讨论如何快速找出字符串内指定字符的下标 于是就出现了下面的写法:

 写法1

var str ="this is javascript"
var resault ={index:"",count:0};

while ( true ){
  var  index =  str.indexOf("s") ;
  if(index == -1) break;
  resault.index += index +",";
  reaault.count++;
}

resault.index = index.subString(0,resault.index.length-1);

console.log("index:"+resault.index);
console.log("count:"+reaault.count);


 

写法2

  var box = "this is javascript";
  for (var i = -1, arr = []; (i = box.indexOf("s", i + 1)) > -1;  arr.push(i));
  alert(arr);

 

记录下,提醒自己基础有多重要……

;