比较JavaScript中动态表中字符串的.length值

时间:2017-05-03 02:32:32

标签: javascript arrays performance

我还是JavaScript新手所以请耐心等待...我有一系列句子......每个单词都需要拆分成一个数组,每个单词的长度都转换为数值,并且值与之比较句子中其他单词的数值,以确定大字符数,并应返回该数字

到目前为止,我有:



function findLongestWord(str) {
	var a = str.split(" "); //array for each word in str
	var b = a.length - 1; //number of cells in array a
	var c = 0; //counter for number of itterations
	var d = []; //array to hold the numberic length of each word per cell
	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
		d[c].push(a[c].length) ; //should push the value of the length of a[c] into d[]
	}  
  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");
&#13;
&#13;
&#13;

例如,在上面的句子中,最长的单词是&#39; jumped&#39;并且应该返回值6 ...我已经在这个工作了几个小时并且试图找到正确的代码...在某一点上代码返回了&#39; 1&#39;,&#39; 3&# 39;或者&#39; 19&#39;其中&#39; 19&#39;通过其中一个句子而不是其他句子...现在我要么得到空白输出或var.push()undefined ....

3 个答案:

答案 0 :(得分: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");

答案 1 :(得分:0)

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

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

答案 2 :(得分:0)

运行代码时出现d[c] is undefined",...错误,因为d是一个空数组。因此,d[0]未定义,您无法在push()上调用undefined。您的代码可以进行一些更正。

&#13;
&#13;
function findLongestWord(str) {
	var a = str.split(" "); //array for each word in str
	var b = a.length; //number of cells in array a
	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++;
  }		
  return Math.max(...d);
}

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

  • 我还用while结构替换了第一个for循环。
  • b不需要等于a.length-1。它应该等于a.length,因为那是你要迭代的数组长度。
  • 对于第二个循环(在数组中查找最大值),您可以使用spread operator。但是如果你想用for循环来做,你应该做一些事情:

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

通常,您可以在for循环中定义循环变量,而不需要声明它。此外,我不认为创建变量是好的做法以防万一