Skip to content Skip to sidebar Skip to footer

Typescript Function Error Can Not Read Proper '' of Null

Cannot Read Property 'split' of Undefined

If you've ever used JavaScript's carve up method, there's a good adventure that yous've encountered the following mistake: TypeError: Cannot read belongings 'split up' of undefined.

There are a few reasons why you would receive this error. Most probable information technology'due south merely 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 Word in a String challenge:

                function findLongestWord(str) {    for(allow i = 0; i < str.length; i++) {     const array = str.split(" ");     array[i].split("");   } }  findLongestWord("The quick chocolate-brown play tricks jumped over the lazy dog");              

it volition throw the TypeError: Cannot read property 'dissever' of undefined mistake.

The split method

When split is called on a string, it splits the string into substrings based on the separator passed in equally an argument. If an empty string is passed as an argument, split treats each character as a substring. Information technology then returns an array containing the substrings:

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

Check out MDN for more details well-nigh split.

The trouble explained with examples

Knowing what the split method returns and how many substrings you lot can wait is the cardinal to solving this claiming.

Permit'southward take another look at the code above and come across why information technology's not working as expected:

                role findLongestWord(str) {    for(let i = 0; i < str.length; i++) {     const array = str.split(" ");     array[i].split("");   } }  findLongestWord("The quick brown play a trick on jumped over the lazy dog");                              

Splitting str into an array like this (const array = str.split(" ");) works every bit expected and returns [ 'The',   'quick',   'brown',   'fox',   'jumped',   'over',   'the',   'lazy',   'canis familiaris' ].

But take a closer wait 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 dark-brown fox jumped over the lazy dog", and if you log str.length to the console, you lot'll get 44.

The terminal statement in the torso of the for loop is what'southward causing the error: array[i].split("");. The length of assortment is 9, and then i would quickly go mode over the maximum length of assortment:

                function findLongestWord(str) {    for(permit i = 0; i < str.length; i++) {     const array = str.split(" ");     console.log(assortment[i]);     // array[0]: "The"     // array[i]: "quick"     // assortment[2]: "chocolate-brown"     // ...     // array[9]: "dog"     // array[10]: undefined     // array[eleven]: undefined   } }  findLongestWord("The quick chocolate-brown fox jumped over the lazy canis familiaris");                              

Calling array[i].split(""); to split each string into substrings of characters is a valid approach, but it volition throw TypeError: Cannot read property 'split' of undefined when information technology'due south passed undefined.

How to solve Detect the Longest Word in a String with dissever

Permit'south apace go over some pseudo code for how to solve this problem:

  1. Split str into an array of individual words
  2. Create a variable to track 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, replace that value with the current word length
  5. Once the length of every word is compared with the maximum word length variable, render that number from the function

First, split str into an array of private words:

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

Create a variable to continue track of the longest discussion length and set it to nothing:

                part findLongestWordLength(str) {   const array = str.split(" ");   let maxWordLength = 0; }              

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

                function findLongestWordLength(str) {   const array = str.split(" ");   let maxWordLength = 0;      for (allow i = 0; i < array.length; i++) {        } }              

Iterate through the array of words and check the length of each give-and-take. Remember that strings too accept a length method yous can call to easily get the length of a string:

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

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

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

Finally, return maxLength at the end of the function, afterward the for loop:

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

Acquire to lawmaking for costless. freeCodeCamp'due south open source curriculum has helped more than 40,000 people get jobs as developers. Become started

berrymigho1965.blogspot.com

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

Postar um comentário for "Typescript Function Error Can Not Read Proper '' of Null"