14.1、问题描述
编写一个函数来查找字符串数组中的最长公共前缀。如果不存在公共前缀,返回空字符串 ""。
- 判断输入的字符串是否是undefined或者为空
- 对数组内的字符串进行对比
- array.reduce( (prev,next) => { } )
- prev 执行一次reduce 之后的返回值
- next 遍历得到的值
- 返回公共前缀 使用 slice()方法切割
- array.reduce( (prev,next) => { } )
- array.reduce()
-
array.reduce(( prev , next , index , array ) => { return //coding ; },initialValue) 参数详解 prev initialValue为可选项 设置了initialValue之后 prev的值就是initialValue 没有设置initialValue prev的值就是数组的第一项 下一次操作之后 prev接收的就是 return之后的返回值 next 数组的每一项(遍历获得的元素) index 数组下标 array 原数组
-
14.2、代码块
var longestCommonPrefix = function (strs) {
// 判断输入的字符串是否是undefined或者为空
if (strs === undefined || strs.length === 0) {
return "";
}
// 对数组内的字符串进行对比
return strs.reduce((prev, next) => {
var i = 0;
// 对获得的字符串每一个字符进行对比
while (prev[i] && next[i] && prev[i] === next[i]) {
// 相等的情况下 继续向后查找并进行对比
i++;
}
// 返回公共前缀 使用 slice()方法切割
return prev.slice(0, i);
}, strs[0])
};
console.log(longestCommonPrefix(["qweasds", "qweaa", "qwer"]));