题目
题目:
从一个句子中找到最短的单词,并返回单词的长度;(单词以空格,隔开)
- findShort(“bitcoin take over the world maybe who knows perhaps”) = 3
- findShort(“turns out random test cases are easier than writing out basic ones”) = 3
- findShort(“a bb ccc”) = 1
- findShort(“aaa bb ccc”) = 2
自己写的方法:
function findShort(s){
let str = [...s],words = [], word ="",len=[];
str.forEach((value)=>{
if(value!=" "){
word=`${word}${value}`;
}else{
words.push(word);
word = "";
}
})
words.forEach((value)=>{
len.push(value.length);
})
return len.sort((a,b)=>a-b)[0];
}
补充:自己的写法一开是使用split(“”)分割单词,成为了字母,注意分割空格使用split(” “); ES6 三点运算符 也是分割位一个一个单词 […s];
使用了多个变量,以及多次遍历,算法不好。接下来学习一下其他大佬们的写法。
大佬一:
function findShort(s){
return s.split(" ").sort((a,b)=>a.length-b.length)[0].length;
}
依旧是Array的sort()方法的巧用,sort()排序,可以自定义排序规则。
这边sort((a,b)=>a.length-b.length); 按照数组内的字符串长度来排序。这样第一个就是最小的字符长度了。
大佬二:
function findShort(s){
return s.split(" ").reduce((a,b)=>{
if(typeof(a) =='string'){
a = a.length;
}
return a < b.length ? a : b.length;
})
}
Array.reduce()方法
定义和用法
reduce()方法接收一个函数作为累加器,数组中的每个值(从左到右)开始缩减,最终计算为一个值。
reduce()可以作为一个高阶函数,用户函数的compose。
- reduce()对于空数组是不会执行回调函数的。//用法
array.reduce((total,currentValue,currentIndex,arr)=>{
},initialValue);
reduce()的参数 :
* function(total,currentValue,index,arr),是reduce()必须的一个参数,用于执行每个数组元素的函数。
- 函数参数:
- total: 必传,初始值,或者计算结束后的返回值。,初始值为遍历数组的第一个数,或者给是初始赋的值。
- currentValue: 必传,当前元素
- currentIndex: 可选,当前元素的索引
- arr: 可选,当前元素所属的数组对象
- initialValue: 可选,传递给函数的初始值。
解析
var a=[1,3,4,5];
var = a.reduce((a,b)=>{
//a,没有初始值时,数组第一个元素赋给a,b即为第二个元素。
//当a有初始值时,b从第一个元素开始
//b只会在a的后面元素
})
大佬三:
function findShort(s){
var ans = s.split(' ')[0].length;
s.split(' ').forEach(x => {
ans = Math.min(ans, x.length);
});
return ans;
}
Math的min()方法和max()方法
大佬四:
function findShort(s){
return Math.min.apply(null,s.split(' ').map(s=>s=s.length));
}
不太理解这位大佬的使用,为何使用Math.min要加一个apply()。但是去掉apply(),则返回NaN。
apply()方法:
说到apply()必定会和call()一起出现。
大佬大佬。
加油,一定要坚持下去。
大佬四那个相当于这句话return Math.min(…s.split(‘ ‘).map(s=>s=s.length));
你才是大佬
我喜欢唱跳rap