2017-05-03 60 views
0

我对JavaScript仍然陌生,所以请耐心等待......我有一系列的句子......每个单词需要分割成一个数组,每个单词的长度转换为数值,比较值的句子中的其他词的数值来确定人物的拉尔数量,应返回数比较JavaScript中动态表中字符串的长度值

到目前为止,我有:

function findLongestWord(str) { 
 
\t var a = str.split(" "); //array for each word in str 
 
\t var b = a.length - 1; //number of cells in array a 
 
\t var c = 0; //counter for number of itterations 
 
\t var d = []; //array to hold the numberic length of each word per cell 
 
\t var e ; //compares cells and returns highest numberic value 
 
    var f = []; //just in case it is needed 
 
    for (a ; c < b ; c++) { //while c is less than b run code and add 1 to c 
 
\t \t d[c].push(a[c].length) ; //should push the value of the length of a[c] into d[] 
 
\t } 
 
    for (c = 0 ; d[c] < d.length ; c++) { 
 
    e = [d[c]].Math.max();//should return the larges value in d[] 
 
    } 
 
    return e; 
 
} 
 
findLongestWord("The quick brown fox jumped over the lazy dog");

例如,在上面的句子中,最长的单词是'jumped',并且应该返回6的值......我一直在努力研究这个小时并试图找到正确的代码......在某一时刻,代码返回了' 1','3'或'19',其中'19'通过了其中一个句子,但没有通过其他语句...现在,我要么获得空白输出或var.push()未定义....

+0

可能的重复:http://stackoverflow.com/questions/17386774/javascript-find-longest-word-in-a-string – jrook

回答

0
function findLongestWord(str) { 
    var words = str.split(" "), 
     word_lengths = []; 

    for (var i=0; i < words.length - 1; i++) { 
    word_lengths[i] = words[i].length; 
    } 

    return Math.max.apply(null, word_lengths); 
} 


findLongestWord("The quick brown fox jumped over the lazy dog"); 
0

将str分解为单词,然后使用Math max查找最长。

function getLongest(str) 
    var maxSize = 0; 
    str.replace(/\w+/g, word => maxSize = Math.max(word.length, maxSize)); 
    return maxSize; 
} 
0

当你运行你的代码,因为d是一个空数组你得到d[c] is undefined",...错误。因此d[0]未定义,您不能在undefined上调用push()。您的代码可以使用一些更正。

function findLongestWord(str) { 
 
\t var a = str.split(" "); //array for each word in str 
 
\t var b = a.length; //number of cells in array a 
 
\t var d = []; //array to hold the numberic length of each word per cell 
 
    
 
    while(c < b) { 
 
    d.push(a[c].length) ; //should push the value of the length of a[c] into d[] 
 
    c++; 
 
    } \t \t 
 
    return Math.max(...d); 
 
} 
 

 
var longest = findLongestWord("The quick brown fox jumped over the lazy dog"); 
 
console.log(longest);

  • 我也取代了第一个for循环带,而构建体。
  • b不需要等于a.length-1。它应该等于a.length,因为这是你想要迭代的数组长度。
  • 对于第二个循环(查找数组中的最大值),可以使用spread operator。但是如果你想用一个循环做到这一点,你应该做的线沿线的东西:

    var max=d[0]; 
    for(var i=1; i<d.length; i++) 
        if(d[i]>max) max=d[i]; 
    

在一般情况下,您可以定义里面的for循环的循环变量,你不需要宣布它。另外,我不认为创建变量以防万一是好的做法。