If you've ever used JavaScript's split
method, there's a good chance that you've encountered the following error: TypeError: Cannot read property 'split' of undefined
.
如果你曾经使用过 JavaScript 的 split 方法,很有可能你遇到了下面的错误: TypeError: Can not read property‘ split’of undefined。
There are a few reasons why you would receive this error. Most likely it's just a basic misunderstanding of how split
works and how to iterate through arrays.
您会收到这个错误的原因有几个。很可能这只是对分割如何工作以及如何遍历数组的基本误解。
For example, if you try to submit the following code for the Find the Longest Word in a String challenge:
例如,如果你尝试提交下面的代码来进行查找字符串中最长的单词的挑战:
function findLongestWord(str) {
for(let i = 0; i < str.length; i++) {
const array = str.split(" ");
array[i].split("");
}
}
findLongestWord(“The quick brown fox jumped over the lazy dog”);
it will throw the TypeError: Cannot read property ‘split’ of undefined
error.
它将抛出 TypeError: Can not read property‘ split’of undefined error。
The split
method
分裂法
When split
is called on a string, it splits the string into substrings based on the separator passed in as an argument. If an empty string is passed as an argument, split
treats each character as a substring. It then returns an array containing the substrings:
当对字符串调用 split 时,它会根据作为参数传入的分隔符将字符串拆分为子字符串。如果将空字符串作为参数传递,则 split 将每个字符视为子字符串。然后返回一个包含子字符串的数组:
const testStr1 = “Test test 1 2”;
const testStr2 = “cupcake pancake”;
const testStr3 = “First,Second,Third”;
testStr1.split(" “); // [ ‘Test’, ‘test’, ‘1’, ‘2’ ]
testStr2.split(”"); // [ ‘c’, ‘u’, ‘p’, ‘c’, ‘a’, ‘k’, ‘e’, ’ ', ‘p’, ‘a’, ‘n’, ‘c’, ‘a’, ‘k’, ‘e’ ]
testStr3.split(","); // [ ‘First’, ‘Second’, ‘Third’ ]
Check out MDN for more details about split
.
有关拆分的更多详细信息,请查看 MDN。
The problem explained with examples
举例说明这个问题
Knowing what the split
method returns and how many substrings you can expect is the key to solving this challenge.
知道 split 方法返回什么以及您可以期望有多少子字符串是解决这个问题的关键。
Let’s take another look at the code above and see why it’s not working as expected:
让我们再看一下上面的代码,看看为什么它不能正常工作:
function findLongestWord(str) {
for(let i = 0; i < str.length; i++) {
const array = str.split(" “);
array[i].split(”");
}
}
findLongestWord(“The quick brown fox jumped over the lazy dog”);
Splitting str
into an array like this (const array = str.split(" “);
) works as expected and returns [ ‘The’, ‘quick’, ‘brown’, ‘fox’, ‘jumped’, ‘over’, ‘the’, ‘lazy’, ‘dog’ ]
.
将 str 分割成这样的数组(const array = str.split (””) ;)可以正常工作并返回[‘ The’、‘ quick’、‘ brown’、‘ fox’、‘ jumped’、‘ over’、‘ The’、‘ lazy’、‘ dog’]。
But 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.
但是仔细看看 for 循环。不使用数组的长度作为迭代 i 的条件,而是使用 str.length。
str
is “The quick brown fox jumped over the lazy dog”, and if you log str.length
to the console, you’ll get 44.
Str 是“ The quick brown fox jumped over The lazy dog”,如果你将 str.length 记录到控制台,你会得到44。
The last statement in the body of the for
loop is what’s causing the error: array[i].split(”");
. The length of array
is 9, so i
would quickly go way over the maximum length of array
:
For 循环体中的最后一条语句是导致错误的原因: array [ i ].split(””) ;。数组的长度是9,所以我会快速地超过数组的最大长度:
function findLongestWord(str) {
for(let i = 0; i < str.length; i++) {
const array = str.split(" ");
console.log(array[i]);
// array[0]: “The”
// array[1]: “quick”
// array[2]: “brown”
// …
// array[9]: “dog”
// array[10]: undefined
// array[11]: undefined
}
}
findLongestWord(“The quick brown fox jumped over the lazy dog”);
Calling array[i].split("");
to split each string into substrings of characters is a valid approach, but it will throw TypeError: Cannot read property ‘split’ of undefined
when it’s passed undefined
.
调用 array [ i ].Split (””) ; 将每个字符串拆分为字符的子字符串是一种有效的方法,但是它会抛出 TypeError: 当未定义的属性被传递时,不能读取该属性的‘ split’。
How to solve Find the Longest Word in a String with split
如何解决字符串中最长单词的分割问题
Let’s quickly go over some pseudo code for how to solve this problem:
让我们快速浏览一些解决这个问题的伪代码:
- Split 分裂
str
into an array of individual words 变成一系列单词 - Create a variable to track the greatest word length 创建一个变量来跟踪最大的单词长度
- Iterate through the array of words and compare the length of each word to the variable mentioned above 循环遍历单词数组,并将每个单词的长度与上面提到的变量进行比较
- If the length of the current word is greater than the one stored in the variable, replace that value with the current word length 如果当前单词的长度大于存储在变量中的单词的长度,则用当前单词长度替换该值
- Once the length of every word is compared with the maximum word length variable, return that number from the function 将每个单词的长度与最大单词长度变量进行比较后,从函数中返回该数字
First, split str
into an array of individual words:
首先,将 str 分成一组单词:
function findLongestWordLength(str) {
const array = str.split(" “);
}
Create a variable to keep track of the longest word length and set it to zero:
创建一个变量来跟踪最长的单词长度,并将其设置为零:
function 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 array.length
in your for
loop:
既然 array 的值是[‘ The’、‘ quick’、‘ brown’、‘ fox’、‘ jumped’、‘ over’、‘ The’、‘ lazy’、‘ dog’] ,那么可以在 for 循环中使用 array.length:
function findLongestWordLength(str) {
const array = str.split(” ");
let maxWordLength = 0;
for (let i = 0; i < array.length; i++) {
}
}
Iterate through the array of words and check the length of each word. Remember that strings also have a length
method you can call to easily get the length of a string:
循环遍历单词数组并检查每个单词的长度。记住,字符串还有一个 length 方法,你可以调用它来轻松得到字符串的长度:
function findLongestWordLength(str) {
const array = str.split(" ");
let maxLength = 0;
for (let i = 0; i < array.length; i++) {
array[i].length;
}
}
Use 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
:
使用 if 语句检查当前单词的长度(数组[ i ])。长度)大于 maxLength。如果是,将 maxLength 的值替换为 array [ i ]。长度:
function findLongestWordLength(str) {
const array = str.split(" ");
let maxLength = 0;
for (let i = 0; i < array.length; i++) {
if (array[i].length > maxLength) {
maxLength = array[i].length;
}
}
}
Finally, return maxLength
at the end of the function, after the for
loop:
最后,在函数的末尾,在 for 循环之后返回 maxLength:
function findLongestWordLength(str) {
const array = str.split(" ");
let maxLength = 0;
for (let i = 0; i < array.length; i++) {
if (array[i].length > maxLength) {
maxLength = array[i].length;
}
}
return maxLength;
}
freeCodeCamp