Skip to content Skip to sidebar Skip to footer

Typeerror: Cannot Read Property "Source" From Undefined.

Cannot Read Property 'split' of Undefined

If you've ever used JavaScript's divide method, in that location's a adept gamble that you've encountered the following error: TypeError: Cannot read property 'split' of undefined.

There are a few reasons why you would receive this fault. Virtually likely it's just a basic misunderstanding of how split works and how to iterate through arrays.

For example, if yous endeavour to submit the following code for the Find the Longest Give-and-take in a Cord challenge:

                function findLongestWord(str) {    for(permit i = 0; i < str.length; i++) {     const array = str.split(" ");     array[i].split("");   } }  findLongestWord("The quick chocolate-brown pull a fast one on jumped over the lazy dog");              

information technology will throw the TypeError: Cannot read property 'split up' of undefined error.

The carve up method

When dissever is called on a string, it splits the string into substrings based on the separator passed in every bit an argument. If an empty string is passed every bit an statement, split treats each graphic symbol as a substring. It and then returns an assortment containing the substrings:

                const testStr1 = "Test test 1 2"; const testStr2 = "cupcake pancake"; const testStr3 = "Start,Second,Third";  testStr1.split(" "); // [ 'Test', 'test', 'ane', 'ii' ] testStr2.split(""); // [ 'c', 'u', 'p', 'c', 'a', 'k', 'e', ' ', 'p', 'a', 'northward', 'c', 'a', 'one thousand', 'e' ] testStr3.split(","); // [ 'Get-go', '2nd', 'Tertiary' ]                              

Check out MDN for more than details about separate.

The problem explained with examples

Knowing what the split method returns and how many substrings yous can look is the key to solving this challenge.

Allow'due south have some other look at the code above and see why it's not working every bit expected:

                office findLongestWord(str) {    for(allow i = 0; i < str.length; i++) {     const array = str.split(" ");     assortment[i].split("");   } }  findLongestWord("The quick dark-brown fox jumped over the lazy dog");                              

Splitting str into an assortment like this (const array = str.divide(" ");) works as expected and returns [ 'The',   'quick',   'brownish',   'fox',   'jumped',   'over',   'the',   'lazy',   'dog' ].

Only take a closer look at the for loop. Rather than using the length of array as a condition to iterate i, str.length is used instead.

str is "The quick brown fox jumped over the lazy canis familiaris", and if you log str.length to the console, you'll get 44.

The last statement in the body of the for loop is what's causing the fault: array[i].split("");. The length of array is 9, and then i would rapidly get way over the maximum length of array:

                function findLongestWord(str) {    for(let i = 0; i < str.length; i++) {     const array = str.divide(" ");     console.log(array[i]);     // array[0]: "The"     // assortment[i]: "quick"     // array[2]: "brown"     // ...     // assortment[nine]: "dog"     // array[ten]: undefined     // array[11]: undefined   } }  findLongestWord("The quick dark-brown fox jumped over the lazy dog");                              

Calling array[i].split(""); to dissever each string into substrings of characters is a valid approach, merely information technology will throw TypeError: Cannot read belongings 'split' of undefined when it'southward passed undefined.

How to solve Find the Longest Word in a String with split

Let's chop-chop go over some pseudo code for how to solve this problem:

  1. Split str into an array of private words
  2. Create a variable to rails the greatest word length
  3. Iterate through the array of words and compare the length of each give-and-take to the variable mentioned above
  4. If the length of the current word is greater than the one stored in the variable, supersede that value with the current word length
  5. Once the length of every word is compared with the maximum word length variable, return that number from the office

First, split str into an array of private words:

                part findLongestWordLength(str) {   const array = str.split up(" "); }              

Create a variable to keep track of the longest word length and prepare information technology to zero:

                office findLongestWordLength(str) {   const array = str.separate(" ");   let maxWordLength = 0; }              

At present that the value of array is ['The', 'quick', 'chocolate-brown', 'fox', 'jumped', 'over', 'the', 'lazy', 'dog'], you tin can use array.length in your for loop:

                function findLongestWordLength(str) {   const assortment = str.carve up(" ");   permit maxWordLength = 0;      for (let i = 0; i < array.length; i++) {        } }              

Iterate through the array of words and check the length of each word. Call up that strings also take a length method you tin call to easily get the length of a cord:

                part findLongestWordLength(str) {   const array = str.split(" ");   allow maxLength = 0;      for (let i = 0; i < array.length; i++) {     array[i].length;   } }              

Utilise an if statement check if the length of the current word (array[i].length) is greater than maxLength. If so, replace the value of maxLength with array[i].length:

                function findLongestWordLength(str) {   const array = str.split(" ");   allow maxLength = 0;      for (let i = 0; i < assortment.length; i++) {     if (array[i].length > maxLength) {       maxLength = array[i].length;     }   } }              

Finally, return maxLength at the end of the part, after the for loop:

                function findLongestWordLength(str) {   const array = str.dissever(" ");   allow maxLength = 0;      for (permit i = 0; i < assortment.length; i++) {     if (assortment[i].length > maxLength) {       maxLength = assortment[i].length;     }   }        return maxLength; }              

Learn to code for free. freeCodeCamp's open up source curriculum has helped more than twoscore,000 people become jobs every bit developers. Get started

mullinstwereper.blogspot.com

Source: https://www.freecodecamp.org/news/cannot-read-property-split-of-undefined-error/

Postar um comentário for "Typeerror: Cannot Read Property "Source" From Undefined."