我正在尝试编写一个函数来返回字符串中最短单词的长度。它只在某些时候有效,我似乎无法弄清楚为什么。
function findShort(s) {
const stringArray = s.split(" ");
// Compares the length of two words, then moves to the next till complete.
// Returns the words in order of length
const orderedArray = stringArray.sort((a, b) => {
return a.length > b.length;
})
//returns the length of the first word(0 index of array)
return orderedArray[0].length;
}
您需要从 sort()
返回一个数字而不是 bool 值。 sort()
函数应该是:
const orderedArray = stringArray.sort((a, b) => {
return a.length - b.length;
})
function findShort(s) {
const stringArray = s.split(" ");
const orderedArray = stringArray.sort((a, b) => {
return a.length - b.length
})
return orderedArray[0].length;
}
console.log(findShort("The quick brown fox ju map"))
您不需要对整个数组进行sort()
,只需使用map()
获取长度数组,然后将其传递给Math.min
const findShort = str => Math.min(...str.split(' ').map(x => x.length))
console.log(findShort("The quick brown fox ju map"))