简体   繁体   中英

Unhandled Rejection (TypeError): Cannot read property 'push' of undefined

i am getting this error, i just want to make a function that return all indexes of an array, but i dont know if i doing something wrong, it just shows an error than push can not be used, becouse undefined value.

here the code:

    function getIindex(array){
      let values
      for (let [ index, value ] of array.entries()) {
        values.push(index)
        console.log(values)
      }  
      return values
    }  

    let indexSubIndustry = getIindex(subRows)

You need to initialize the values variable with a value, empty array in your case.

function getIindex(array){
  let values = []; // here
  for (let [ index, value ] of array.entries()) {
    values.push(index)
    console.log(values)
  }  
  return values
}  

let indexSubIndustry = getIindex(subRows)

You might need to specify type hint for that array, depending on your TS configuration (eg with strict mode enabled).

let values: number[] = [];

Btw your code can be simplified a lot, if you want to return keys of the array parameter, just use keys() method:

function getIindex(array){
  return [...array.keys()]; // convert iterator to array
}  

You should assign your values as an empty array instead of keeping it undefined.


let values = [];

// Rest of the code

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