[英]find the shortest word in an array
id 想获取数组中最短的单词。 即使“ei”是最短的,这也会返回第一个单词“bil”。 我如何定义一个词比其他词短?
const words= ['bil', 'plante', 'kaffe', 'bog', 'ei', 'planetarium'];
function getShortestWord() {
for(let i = 0; i < words.length; i++) {
const strSplit = words[i].split('');
let lengthOfWord = strSplit.length;
if(strSplit[i].length < lengthOfWord) {
lengthOfWord = strSplit[i].length
}
return lengthOfWord
}
}
getShortestWord()
按长度对数组进行排序。
const words = ["bil", "plante", "kaffe", "bog", "ei", "planetarium"]; let ret = words.sort((x, y) => x.length - y.length); console.log(ret[0]);
const wordsArray = [ 'bil', 'plante', 'kaffe', 'bog', 'ei', 'planetarium' ]; function shortestWordInArray(words){ let result = ""; words.forEach( word => { word.length < result.length ? result = word : null } ) console.log(result) return result; } shortestWordInArray(wordsArray)
这将是我的方法,迭代项目并存储更长的时间。
您需要修复 return 和 split 语句。 您正在使用数组,因此不需要 split 语句。
function getShortestWord() {
if(words == null || words.length < 1) {
return words; // handling empty array
}
let minLengthWord = words[0];
for(let i = 1; i < words.length; i++) {
if(words[i].length < minLengthWord.length) {
minLengthWord = words[i];
}
}
return lengthOfWord
}
注意: return
语句在for
循环之外。 因为我们需要找到最短的单词,只有遍历整个数组才能知道。
您需要实际跟踪并返回您确定最短的单词。 另外, string.length 会直接给你长度。 请注意,为了您的学习目的,我试图尽可能接近您的概念。 :)
const words= ['bil', 'plante', 'kaffe', 'bog', 'ei', 'planetarium'];
function getShortestWord() {
let shortest = 0;
for(let i = 0; i < words.length; i++) {
if(words[i].length < words[shortest].length) {
shortest = i
}
}
return words[shortest]
}
let shortest = getShortestWord()
console.log("Shortest = " + shortest)
只需遍历存储第一个元素作为当前最短单词的数组进行比较,如果另一个字符串的长度较短,则将其设为当前最短的单词,否则继续循环并检查,最后返回该单词,因为它是中最短的单词那个数组
const words = ['bil', 'plante', 'kaffe', 'bog', 'ei', 'planetarium']; function getShortestWord(w) { let shortestWord = w[0]; for(let i = 1;i < w.length; i++) { // it's just short circuit condition shortestWord.length > w[i].length && (shortestWord = w[i]); } return shortestWord; } console.log(getShortestWord(words));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.