猿问

js计算数组连续的最大长度问题

假如有一个数组
var arr=[1,2,4,5,6,8,9,10,11]
怎么计算最大的连续长度 也就是4

不负相思意
浏览 648回答 1
1回答

哆啦的时光机

我写了一下!这个解释都在注释那里了,看了就明白了!function countLen(arr){&nbsp; &nbsp; //如果参数不是数组或者长度为0,直接返回0&nbsp; &nbsp; if(arr.constructor!==Array||arr.length===0){return 0;}&nbsp; &nbsp; //首先进入当前连续长度nowLen设初始化为1,最大连续长度maxLen初始化为0&nbsp; &nbsp; var nowLen=1,maxLen=0;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; for(var i=1,len=arr.length;i<len;i++){&nbsp; &nbsp; &nbsp; &nbsp; //当前数组元素是不是比上一个数组大1&nbsp; &nbsp; &nbsp; &nbsp; if(arr[i]-arr[i-1]===1){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; //如果是,当前连续长度nowLen+1&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; nowLen++;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; else{&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; //否则先判断,当前连续长度是否大于最大连续长度&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if(maxLen<nowLen){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; //如果是就赋值&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; maxLen=nowLen&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; //当前连续长度初始化为1&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; nowLen=1;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; //循环完再判断一次当前连续长度是否大于最大连续长度(避免最大连续长度是数组最后面几个数组时产生的bug)&nbsp; &nbsp; if(maxLen<nowLen){&nbsp; &nbsp; &nbsp; &nbsp; maxLen=nowLen&nbsp; &nbsp; }&nbsp; &nbsp; //返回最大连续长度&nbsp; &nbsp; return maxLen;}
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答