我正在通过编写一些处理排序和搜索无序列表的函数来练习Javascript。我已经写了几个函数,但是突然遇到了这个错误,我不确定为什么。如果我可以找到解决此错误的指导。
这是我的代码
function sortlength(){
formarray();
for(i=0;i<wordarray.length;i++){
if(wordarray[i].length > wordarray[i+1].length){
temp = wordarray[i];
wordarray[i] = wordarray[i+1];
wordarray[i+1] = temp;
}
}
toDOM();
}
这是错误
Uncaught TypeError: Cannot read property 'length' of undefined
由于某种原因,错误似乎指向wordarray [i + 1] .length,而不是wordarray [i] .length。
P.S formarray()从页面上的单词列表中形成一个数组,它获取每个列表项的innerHTML,toDOM()将数组放回页面中
formarray()根据要求
var list = document.getElementById("list");
var words = list.getElementsByTagName("li");
var wordarray = [];
function formarray(){//forms array from list on page
for(i=0;i<words.length;i++){
wordarray[i] = words[i].innerHTML;
}
return wordarray;
}
控制台中的wordarray显示如下
wordarray
(200) ["servant", "watch", "wound", "women", "visitor", "stop", "lip", "excited", "scatter", "soda", "texture", "relax", "white", "thaw", "money", "noxious", "vulgar", "smiling", "imported", "embarrass", "prevent", "uptight", "powder", "base", "charge", "premium", "jump", "welcome", "ultra", "condition", "righteous", "fall", "pop", "decorate", "capricious", "alluring", "kick", "adjoining", "optimal", "amuck", "impulse", "grandiose", "regret", "sky", "absurd", "push", "unbecoming", "loaf", "amount", "wilderness", "eager", "board", "name", "guide", "difficult", "unarmed", "naughty", "puncture", "embarrassed", "symptomatic", "sand", "tick", "jumbled", "pleasant", "shake", "spotless", "womanly", "average", "steady", "motionless", "action", "valuable", "mass", "paddle", "scared", "moor", "squealing", "graceful", "drip", "tacky", "devilish", "quince", "face", "observant", "mice", "plain", "bored", "tough", "delightful", "change", "morning", "business", "adjustment", "reproduce", "spiky", "zonked", "dime", "contain", "rain", "unused", …]
答案 0 :(得分:0)
尝试更改为:
<div style="float: left; width: 180px; clear: both;">Foo</div>
<div style="float: left; width: 180px;">Bar</div>
我认为您超出了范围。您应该迭代直到索引function sortlength(){
formarray();
for(i=0;i < wordarray.length - 1;i++){
if(wordarray[i].length > wordarray[i+1].length){
temp = wordarray[i];
wordarray[i] = wordarray[i+1];
wordarray[i+1] = temp;
}
}
toDOM();
}
,以便在调用wordarray.length - 2
时获得最后一次迭代中的最后一个元素。否则,您将超出范围。