简体   繁体   English

JavaScript 未定义数组索引

[英]JavaScript undefined array index

Beginner here.初学者在这里。 I was doing this exercise from Coding Addict.我在 Coding Addict 做这个练习。

The exercise:练习:

 function longestWords(str){ let words = str.split(" "); let size = 0; let max = ['']; for(let i=0; i<words.length; i++){ if(words[i].length >= size){ size = words[i].length; if(max[max.length-1].length <words[i].length){ max = []; max.push(words[i]); } else{ max = [...max,words[i]]; } } } return [...max]; } console.log(longestWords("I woke up early today")); console.log(longestWords("I went straight to the beach"));

Now, When I tried changing the index for max[] array to i .现在,当我尝试将max[]数组的索引更改为i时。

if(max[i].length <words[i].length){

I got this error:我收到了这个错误:

Uncaught TypeError: Cannot read property 'length' of undefined at longestWords未捕获的类型错误:无法读取最长单词处未定义的属性“长度”

Can someone tell me why I can't change the index and have to use max.length-1 instead?有人可以告诉我为什么我不能更改索引而必须改用max.length-1吗?

When you use i, it represents the individual word in str.当你使用 i 时,它代表 str 中的单个单词。 For example, "I woke up early today" has 5 words( or length = 5 ), but your max array has only 1 in length (which is '').例如,“我今天早起”有 5 个单词(或长度 = 5),但您的最大数组长度只有 1(即 '')。 So if you use i to access max array you will get index out of bound.因此,如果您使用 i 访问最大数组,您将获得超出范围的索引。 Unless you use the str has the same length as max.除非您使用 str 的长度与 max 相同。

because your max array has always one element so there is no entry in the index 1 which is max[max.length], so you better actually write it as max[0] instead.因为您的最大数组始终只有一个元素,所以索引 1 中没有条目,即 max[max.length],因此您最好将其实际写为max[0]

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

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