Search code examples
for-loopgoogle-apps-scriptgoogle-sheetsoff-by-one

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.

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])
      }
    }