[英]TypeError: Cannot read properties of undefined (reading 'length')
i tried to make a function that sort an array based from it's length我试图制作一个函数,根据数组的长度对数组进行排序
function sortingByLength(array) {
for (let i = 0; i < array.length; i++) {
if (array[i + 1].length > array[i].length) {
smol = array[i];
array[i] = array[i + 1];
array[i + 1] = smol;
i = -1;
}
}
return array;
}
let testPack = ["Chicken", "Monkeys", "Foxy"];
while it had no error whatsoever, it shows虽然它没有任何错误,但它显示
TypeError: Cannot read properties of undefined (reading 'length')
and the error pointer shows错误指针显示
c:\......................\Special-Training-1\9.js:18
if (array[i + 1].length > array[i].length) {
^
i tried to debug it with node in vscode run and debug, it was doing things as normal, all parameter read normal.我尝试在 vscode 运行和调试中用节点调试它,它正常运行,所有参数读取正常。 i watched grouping, array[i].length and array[i+1].length.
我看了分组,array[i].length 和 array[i+1].length。 i read there's possibilities that i had same variable down in line it can happens but no, i don't have any variable named 'array' or 'length'
我读到有可能我有相同的变量,它可能会发生但不,我没有任何名为“array”或“length”的变量
i did try, just removing the length at all.我确实尝试过,只是完全删除了长度。 but it doens't work as i need to compare the length and rearrange it inside the array itself.
但它不起作用,因为我需要比较长度并在数组本身内重新排列它。
for notes: i can't use proper built in function such as forEach, every, splice, slice and such.注意事项:我不能使用适当的内置函数,例如 forEach、every、splice、slice 等。 however i can use for loop and for.. of.
但是我可以使用 for 循环和 for.. of. and i can't use any array built in besides.push()
而且我不能使用任何内置的数组 besides.push()
i missed the limitation on the length.我错过了长度限制。 thanks for vicki on pointing that out.
感谢 vicki 指出这一点。 i did this in number, and it works just fine.
我做了很多,效果很好。 so i reused this in array of strings, and it failed.
所以我在字符串数组中重复使用了它,但它失败了。 i used
我用了
i < array.length - 1
我 < array.length - 1
and it works just fine它工作得很好
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.