简体   繁体   中英

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. i watched grouping, array[i].length and 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'

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. however i can use for loop and for.. of. and i can't use any array built in besides.push()

i missed the limitation on the length. thanks for vicki on pointing that out. 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

and it works just fine

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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