简体   繁体   English

找到最长的单词之前先分割一个字符串

[英]Splitting a string before finding longest word

I have read a few different posts on this so I am sorry to ask this again but none seemed to solve my issue. 我已经阅读了一些不同的帖子,所以很抱歉再次提出这个问题,但是似乎没有一个可以解决我的问题。

I'm trying to draw out the length of the longest word in a string, that is coming from HTML. 我试图绘制字符串中最长单词的长度,该长度来自HTML。

All I can get is, "Uncaught TypeError: Cannot read property 'split' of undefined" 我所能获得的就是“未捕获的TypeError:无法读取未定义的属性'split'”

The HTML: HTML:

<p id="p">I'm looking for the longest length of a word in this sentence</p>
<button onclick="longestWordFunc()">Click</button>

The JS: JS:

var myString = document.getElementById("p");


function longestWordFunc(myString) {
  var stringSplit = myString.split(" ");
  var longestWord = 0;

  for(var i = 0; i < stringSplit.length; i++){
    if(longestWord >= stringSplit[i].length){

      longestWord = stringSplit[i].length;   
    }
   }

  return longestWord;
 }

Use reduce to iterate over the array starting with an empty string and return the longest of the two on each iteration. 使用reduce可以从空字符串开始迭代数组,并在每次迭代中返回两者中最长的一个。

The reason you are getting the undefined error is because myString is a parameter of your function and you are passing nothing into it, hence undefined. 出现未定义错误的原因是因为myString是函数的参数,并且没有向其中传递任何内容,因此未定义。

 var myString = document.getElementById("p").innerText; function longestWordFunc() { return myString.split(" ").reduce((longest, current) => current.length > longest.length ? current : longest, ''); } 
 <p id="p">I'm looking for the longest length of a word in this sentence</p> <button onclick="console.log(longestWordFunc())">Click</button> 

Try this: 尝试这个:

 <p id="p">I'm looking for the longest length of a word in this sentence</p>
 <button onclick="longestWordFunc()">Click</button>

In your JS, try adding .innerHTML to the end of your myString function. 在您的JS中,尝试将.innerHTML添加到myString函数的末尾。 Also it was checking for 0 to be greater than or equal to the current stringSplit element. 另外,它还在检查0是否大于或等于当前的stringSplit元素。

 function longestWordFunc() {
     var myString = document.getElementById("p").innerHTML;
     var stringSplit = myString.split(" ");
     var longestWord = 0;

    for(var i in stringSplit) {
        if(longestWord <= stringSplit[i].length){
        longestWord = stringSplit[i].length;   
    }
    return longestWord;
 }

I see one problem and one possible one. 我看到一个问题,一个可能的问题。

  1. The inequality is reversed, should be longestWord < stringSplit[i].length 不等式反转,应为longestWord < stringSplit[i].length

  2. Perhaps you are defining myString before the element is created? 也许您在创建元素之前就定义了myString (Eg, in the head of the html). (例如,在html的头部)。 That might be why myString is undefined. 这可能就是为什么myString未定义的原因。 One solution for this is to move the definition into the function call, so that myString is only defined when the button is clicked. 一种解决方案是将定义移到函数调用中,以便仅在单击按钮时定义myString

     function longestWordFunc() { var myString = document.getElementById("p") var stringSplit = myString.textContent.split(" "); var longestWord = 0; for(var i = 0; i < stringSplit.length; i++){ if(longestWord < stringSplit[i].length){ longestWord = stringSplit[i].length; } } return longestWord; } 

Try this: 尝试这个:

 var text = "I'm looking for the longest length of a word in this sentence" findLongestWord = (str) => { let split = str.split(" "); let longest = ""; split.forEach((word) => { if (word.length > longest.length) { longest = word; } }); return longest; } let longest = findLongestWord(text); console.log(`Longest Word: ${longest} - ${longest.length}`); 

If you just want the length of the longest word instead of returning the word itself you can have the findLongestWord function return this: 如果只需要最长单词的长度而不是返回单词本身,则可以使用findLongestWord函数返回以下内容:

return longest.length

Hope this helps. 希望这可以帮助。

Using reduce as Adrian explained is a great way to achieve your goal in JS. 如Adrian所述,使用reduce是实现JS目标的一种好方法。

But if your target was to learn some of the basics of coding, here are some hints on how to make your current code work. 但是,如果您的目标是学习一些编码基础知识,那么这里有一些有关如何使当前代码正常工作的提示。

 function longestWordFunc() { var myString = document.getElementById("p").innerText; // Just the inner text var stringSplit = myString.split(" "); var longestWord = 0; //Index of longest word var longestLength=0; //Length of longest word for(var i = 0; i < stringSplit.length; i++){ if(stringSplit[i].length>longestLength){ // The other way around longestLength = stringSplit[i].length; longestWord=i; } } console.log(stringSplit[longestWord]); return stringSplit[longestWord]; } 
 <p id="p">I'm looking for the longest length of a word in this sentence</p> <button onclick="longestWordFunc()">Click</button></br> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM