显示数组中最大的单词

时间:2017-04-20 10:54:47

标签: javascript arrays

我想要显示我的数组中最大的单词(包含最多的字符)。到目前为止,如果某人输入'cat'和'mouse',则下面的消息将显示在'mouse contains 5 characters'字样下方。 这是最简单的方法。另外,当输入字段中没有输入任何内容时,“Name:Empty”是如何显示的。

var array = [];
var Return;


function begin() {
var character = "Display words:";
var i = array.length

if (character.trim() === "") {
character = "Name: Empty"

}


  document.getElementById('ErrorOutput').innerHTML = character
  while (i--) {
  document.getElementById('message').innerHTML = array[i] + "<br/>" + document.getElementById('message').innerHTML;
}
}

function addwords() {

  Return = document.getElementById('input').value;
  array.push(Return);
}
<body>
<input type="text" id=input></input>
<button onclick="addwords()" class="button" type = "button">enter words</button><br><br>
<button onclick="begin()" class="button" type = "button">display words</button><br><br>
<p id="ErrorOutput"></p>
<p id="message"></p>
</body>

3 个答案:

答案 0 :(得分:1)

要获取数组中的最大单词,可以按元素长度对数组进行排序:

&#13;
&#13;
var arr = ['asdfa', 'asd', 'asdfasfasdfasdfasdfas', 'sd'];

arr.sort((a, b) => b.length - a.length);
console.log(arr[0])
&#13;
&#13;
&#13;

使用@Yeldar Kurmangaliyev评论更快或更快:

&#13;
&#13;
var arr = ['asdfa', 'asd', 'asdfasfasdfasdfasdfas', 'sd'],
    longestWord = {word: '', len: 0};

arr.forEach(w => {
  if (longestWord.len < w.length) {
    longestWord.text = w;
    longestWord.len = w.length;
  }
});

console.log(longestWord.text, longestWord.len);
&#13;
&#13;
&#13;

答案 1 :(得分:0)

while (i--) { document.getElementById('message').innerHTML = array[i] + "<br/>" + document.getElementById('message').innerHTML;

在这里,通过循环,您可以打印所有单词。

您可以使用reduce函数轻松找到数组中最长的元素:

var longest = array.reduce(function (p, n)  { 
    if (p.length >= n.length) return p;  
    else return n; 
});

最后

document.getElementById('message').innerHTML = longest;

答案 2 :(得分:0)

在这里,我为你制作了简单的片段。 函数 getTheLongestWord 使用带字符串的数组,并将最长的单词作为字符串返回。

var anArray = ["word", "longerWord", "theLongestWordInKnonUniverse", "notThatLongWord"];

function getTheLongestWord(a) {
  var longest = 0;
  var longestIndex = 0;
  for (var i = 0; i < a.length; i++) {
    var length = a[i].length;
    if (length > longest) {
      longest = length;
      longestIndex = i;
    }
  }
  return a[longestIndex];
}

document.getElementById("placeHolder").innerHTML = getTheLongestWord(anArray);
<div id="placeHolder"></div>