给出一个字符串,查找字符串中最长的子字符,并返回其长度数组
findLongestWord("Google do a barrel roll")
字符串分割函数
循环断定,暂存较大值code
循环结束,返回最大值变量的长度索引
function findLongestWord(str) { var newArr = str.split(" "), maxStr = newArr[0]; for(var i=0;i<newArr.length;i++) { if(newArr[i].length > maxStr.length) maxStr = newArr[i]; } return maxStr.length; } findLongestWord("Google do a barrel roll"); //6
切割字符串为数组字符串
使用arr.reduce()调用Math.max()返回数组最大值回调函数
function findLongestWord(str) { return str.split(' ').reduce(function(x,y) { return Math.max(x,y.length); },0) } findLongestWord("Google do a barrel roll"); //6
1.切割字符串为数组
2.判断索引0,1的长度,若是0<1,则删除1,返回自身函数;
若是0>1,则返回从自身函数,参数为从1开始的新字符串it
function findLongestWord(str) { var newArr = str.split(" "); if(newArr.length === 1) { return newArr[0].length; } else if(newArr[0].length >= newArr[1].length) { newArr.splice(1,1); return findLongestWord(newArr.join(" ")); } else { return findLongestWord(newArr.slice(1,newArr.length).join(" ")); } } findLongestWord("Google do a barrel roll"); //6
str.split()
返回一个根据参数分割字符串为包含其子字符的数组,不改变原字符串io
array.reduce(function(accumulator, currentValue, currentIndex, array), initialValue)
reduce 为数组中的每个元素依次执行回调函数,不包括数组中被删除或从未被赋值的元素function
回调函数第一次执行时,accumulator 和 currentValue 的取值有两种状况:调用 reduce 时提供initialValue,accumulator 取值为 initialValue ,currentValue 取数组中的第一个值;没有提供 initialValue ,accumulator 取数组中的第一个值,currentValue 取数组中的第二个值。变量
Math.max()
返回一组数中的最大值。
arr.join()
返回数组中全部元素的链接起来的字符串,参数默认为','
arr.slice(begin,end)
根据返回一个从开始参数到结束参数的新数组,不改变原数组
有其余好的方法或思路的道友,不妨在沙发区神交一番。