帮助了 AmazingCounters.com 位小伙伴

js 取到相同的字符串 返回对应的下标

 

 

["aaa","aaa","","ddd","eee","eee","eee","eee","eee","eee","yyy","zzz","ggg","ggg"]

  有这么一个数组,中间有一段字符串是相同的,我们不知道是什么字符串,现在,请求出中间相同一段的起止下标以及内容

 


var rest=[];
var array=["aaa","aaa","","ddd","eee","eee","eee","eee","eee","eee","yyy","zzz","ggg","ggg"];
array.forEach(function (v,i) {
var sameInLeft=array[i]==array[i-1]?1:0;
var sameInRight=array[i]=array[i+1]?1:0;
if(sameInLeft+sameInRight==1){
rest.push(i);
}

});
for(var i=0;i<rest.length/2;i++){
var indexArr=[rest[i*2],rest[i*2+1]];
//排除收尾连续
if(indexArr[0]!=0&& indexArr[1]!=(array.length-1)){
console.log(indexArr,array.slice(indexArr[0],indexArr[1]+1))

}

}

 

 ——》

[4, 5] [1, 1]
 [6, 7] [1, 1]
 [8, 9] [1, 1]
 [10, 11] [1, 1]
 [12, undefined] []

posted on 2016-07-29 10:04  云的旋律  阅读(4893)  评论(0编辑  收藏  举报

导航

前端攻城狮分享群