初学者在这里。我是在《编码成瘾者》中进行这项练习的。
练习:
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){
我收到此错误:
Uncaught TypeError:最长无法读取未定义的属性“ length”
有人可以告诉我为什么我不能更改索引而不得不使用它max.length-1
吗?
当您使用i时,它表示str中的单个单词。例如,“我今天早起”有5个字(或length = 5),但是您的max数组只有1个长度(即”)。因此,如果使用i访问最大数组,则索引将超出范围。除非您使用str,否则其长度与max。相同。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句