Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why does this reverse loop give me an error in Google Apps Script?

This reverse loop is giving me the error TypeError: Cannot read property '0' of undefined and I can’t find out why.

Here’s the code part:

function formatBoqPipework() {
  const ss = SpreadsheetApp.getActiveSpreadsheet();
  const boqPipeworkSheet = ss.getSheetByName('BOQ Pipework');
  const boqPipeworkRng = boqPipeworkSheet.getRange(5, 1, boqPipeworkSheet.getLastRow(), 14);
  const boqPipeworkValues = boqPipeworkRng.getValues();

  let lastRow = boqPipeworkSheet.getLastRow();

  for (let a = boqPipeworkValues.length; a >= 0; a--) {
    Logger.log(a)
    if (boqPipeworkValues[a][0] == 'Pipework' || boqPipeworkValues[a][0] == '') {
      //let row = a + 5
      boqPipeworkSheet.deleteRow(a+5);
    }
  }
}

Appreciate any help.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Regards,
Antonio

>Solution :

Arrays are 0 based and the .length will give you the "human" length. So in the example below (what will error out) you assign 4 to i and arr[4] does not exist. Because the array number is max 3 if you count from 0.

Error:

function test(){
  const arr = [[1,2],[2,2],[3,2],[4,2]];
  
  console.log(arr.length) // Returns 4
 
  for (let i = arr.length; i >= 0; i--){
    console.log(arr[i][0])
  }
}

So add a -1 after the .length:

function test(){
  const arr = [[1,2],[2,2],[3,2],[4,2]];
  
  for (let i = arr.length - 1; i >= 0; i--){
    console.log(arr[i][0])
  }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading