Javascript Mental Jumpstart

时间:2016-10-16 18:42:22

标签: javascript

我需要一些关于学校作业的帮助,而且我有点卡住了。这个问题定义了以下内容,我需要一个精神上的快速启动;"我似乎无法记住该怎么做才能开始。

function get_longest_word(){
 //Task 1, complete this function to find the longest word
 //from the text entered into the textarea.
 //Once the longest word is found display the longest word in an alert.
 //Hint use the split(" ") method to split the string into an array of words.
 var str = document.getElementById('input_text').value;//str is the string from the input text area
 var longest_word = "not yet implementd";
 alert(longest_word);

3 个答案:

答案 0 :(得分:1)

这样的事情会起作用:

"use strict";

let text = "Hello world, or maybe worlds. Can you guess what is the longest word here ?";
let max = 0, word;

text.split(' ').forEach(e => e.length > max ? (max = e.length, word = e) : null);
console.log(max, word);

这样做的基本上是用空格分隔的单词和数组:

console.log(text.split(' ')); //["Hello", "world,", "or", "maybe", "worlds.", "Can", "you", "guess", "what", "is", "the", "longest", "word", "here", "?"]

然后,我们遍历该列表的每个元素。有很多方法可以做到这一点,我个人选择使用.forEach迭代列表,它接收callback,在这种情况下它将是为数组的每个元素调用的函数。 / p>

回调以Arrow Function的形式提供,它将数组的元素作为参数并用它做一些有趣的事情。语法非常简单。 e => ....

左侧的元素是参数,我称之为e,右侧是返回值,它确实无关紧要,因为回调并不意味着返回任何有用的东西

我使用的返回值是:

e.length > max ? (max = e.length, word = e) : null;

检查当前元素的长度是否大于最大长度max,如果它超过我们设置元素的最大长度并将最长的单词word设置为当前元素。否则,我们什么都不做。

注意:旧浏览器,IE和Safari不支持箭头功能。 Allways检查MDN和其他资源以获取新功能的支持。

注2:e => ....相当于function(e) { return ....; }

希望这有帮助,干杯。

答案 1 :(得分:0)

为了不为你做功课,这就是你要求的;一个快速启动。

var str = "One,two,three,four";
var res = str.split(",");

上面的代码会将字符串拆分为一个字符串数组,用逗号分隔。不知何故,尝试使用此(您需要更改它)与循环结合使用以找到答案。

还值得注意的是,您可以从length属性中获取字符串的长度。

我不会给你更多......

答案 2 :(得分:0)

  • 使用split函数获取字符串数组(如果你不知道如何使用google)
  • 将第一个单词保存为longest_word
  • 现在使用for循环。检查下一个单词是否更长。如果是这样,请将其保存为longest_word。