簡體   English   中英

JavaScript 未定義數組索引

[英]JavaScript undefined array index

初學者在這里。 我在 Coding Addict 做這個練習。

練習:

 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"));

現在,當我嘗試將max[]數組的索引更改為i時。

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

我收到了這個錯誤:

未捕獲的類型錯誤:無法讀取最長單詞處未定義的屬性“長度”

有人可以告訴我為什么我不能更改索引而必須改用max.length-1嗎?

當你使用 i 時,它代表 str 中的單個單詞。 例如,“我今天早起”有 5 個單詞(或長度 = 5),但您的最大數組長度只有 1(即 '')。 因此,如果您使用 i 訪問最大數組,您將獲得超出范圍的索引。 除非您使用 str 的長度與 max 相同。

因為您的最大數組始終只有一個元素,所以索引 1 中沒有條目,即 max[max.length],因此您最好將其實際寫為max[0]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM