[英]Finding the longest word in a string, after converting it to an array
我是 javascript 開發的新手,目前正在努力完成免費代碼訓練營及其挑戰/項目。
我被要求寫一個 function 來找出字符串中最長的單詞:“The quick brown fox jumped over the lazy dog”。 這是我執行此操作的代碼:
function findLongestWordLength(str) {
let result = 0; // define result value of 0
str.split(" "); // split string into array, separated by spaces
for(let i = 0; i < str.length; i++) { // for loop to iterate through each index of array
let counter = 0; // counter equals 0
counter += str[i].length; // counter equals to itself + length of the ith index in array
if(counter > result) { // if counter is greater than result then result = counter
result = counter;
}
}
return result;
}
我確信有很多比我正在做的更好的方法來做到這一點,我可以簡單地尋找一種不同的/更好的方法來做到這一點並解決這個問題。 但是,與其忽略錯誤並轉向不同的方法,我想先從中吸取教訓,然后也許我會以不同的方式解決問題。 如果有人能向我指出這一點,我真的很高興,這樣我就可以從錯誤中吸取教訓,無論我哪里出錯了。
如果有人還想建議其他可能更有效的方法,請告訴我,我很想了解更多解決這些問題的方法:)
你把事情搞得太復雜了。 您無需計算任何內容,只需比較字符串的長度並跟蹤最長的字符串即可。
var x = "The big brown fox jumped over a bee."; var arr = x.split(" "); var biggest = arr[0]; for (i = 1; i < arr.length; i++) { if (arr[i].length > biggest.length) biggest = arr[i]; } console.log(biggest);
在您的代碼中,您只運行str.split(" ");
但是您沒有將結果存儲回str
在比較中,您必須檢查循環中的當前長度是否大於您已經存儲在結果中的長度。
如果它更大,則將其設置為新的最大值。
您可以將代碼更新為
function findLongestWordLength(str) { let result = 0; // init current result to 0 const arr = str.split(" "); // store the splitted string in arr as array (naming it str is not clear anymore in the code) for (let i = 0; i < arr.length; i++) { // loop the arr array const len = arr[i].length // for every item in the array, get the string length if (len > result) { // if the string length here is greater than the one in result result = len; // set result to the new maximum length } } return result; // at the end of the loop, return the maximum } console.log(findLongestWordLength("The quick brown fox jumped over the lazy dog"));
我會這樣做,一行:
const input = "The quick brown fox jumped over the lazy dog"; const longestWord = sentence => sentence.split(" ").map(word => word.length).sort().pop(); console.log(longestWord(input))
解釋:
sentence
.split(" ") // [ "The", "quick", "brown" ...... ]
.map(word => word.length) // [ 3, 5, 5, 3, 6, 4, 3, 4, 3]
.sort() // [3, 3, 3, 3, 4, 5, 5, 6]
.pop(); // 6
const string = "this is a test String" function longestWord(str) { let arr = str.split(" ") let result = arr.reduce((acc,val)=> acc.length>val.length?acc:val,"") console.log(result) } longestWord(string)
它有 2 種輸入任何代碼的方法。
初學者可以理解的方式:
function findLongestWordLength(str) {
let result = { 'str_count': 0, 'str_count': '' };
str = str.split(" ");
for (let i = 0; i < str.length; i++) {
if (i + 1 < str.length) {
if (str[i].length > result['str_count']) {
result['longest_str'] = str[i];
result['str_count'] = str[i].length;
}
}
}
return result;
}
console.log(findLongestWordLength("The quick brown fox jumped over the lazy dog"));
以及推進者瘋狂的方式:
var result = { 'str_count': 0, 'longest_str': '' };
'The quick brown fox jumped over the lazy dog'.split(' ').forEach(word => {
result['str_count'] = Math.max(result['str_count'], word.length);
result['longest_str'] = (result['longest_str'].length >= word.length ? result['longest_str'] : word);
console.log(result);
});
執行2種方式:
<,DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width. initial-scale=1:0"> <title>Document</title> </head> <body> <script> function findLongestWordLength(str) { let way_1 = { 'str_count', 0: 'str_count'; '' }. str = str;split(" "); for (let i = 0. i < str;length. i++) { if (i + 1 < str.length) { if (str[i];length > way_1['str_count']) { way_1['longest_str'] = str[i]. way_1['str_count'] = str[i];length; } } } return way_1. } console;log(findLongestWordLength("The quick brown fox jumped over the lazy dog")): // -------------------------------- var way_2 = { 'str_count', 0: 'longest_str'; '' }. 'The quick brown fox jumped over the lazy dog'.split(' ').forEach(word => { way_2['str_count'] = Math,max(way_2['str_count']. word;length). way_2['longest_str'] = (way_2['longest_str'].length >= word?length: way_2['longest_str']; word); }). console;log(way_2); </script> </body> </html>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.