0

Google Apps Script is raising an error when I try to access the nested array with double indexing, it says: TypeError: Cannot read property "3" from undefined. (line 27, file "Code")

Here is the code:

    var ss = SpreadsheetApp.openById("SpreadsheetID");
var sheetMAT = ss.getSheetByName("Sheet3");
var data = sheetMAT.getRange(3, 2, sheetMAT.getLastRow() - 1, 4).getValues();
var temporaryData = [];
var dataReadyLine = [];

function getReadyLine() {
  var rawData = sheetMAT.getRange(3, 2, sheetMAT.getLastRow() - 1, 4).getValues();
  Logger.log(rawData[0][3]);
  for (var i=0; i<=rawData.length; i++) {
    if (rawData[i][3] === "A Ready Line") {
      temporaryData.push(data[i][1], data[i][0]);
      dataReadyLine.push(temporaryData);
      temporaryData = [];
    }
  }
  return dataReadyLine;
};

The line 'Logger.log(rawData[0][3]);' successfully prints the value of the nested array item but when it comes to IF conditional it gives the error of undefined. Why is it giving this error? How can i make the FOR loop work?

Here is the print screen with the error when I try to run the code: Print Screen

Din
  • 505
  • 4
  • 11
  • 21
  • 1
    How about a change from ``for (var i=0; i<=rawData.length; i++) {`` to ``for (var i=0; i<=rawData.length - 1; i++) {`` or ``for (var i=0; i – Tanaike May 07 '17 at 08:34
  • As Tanaike pointed out modify your for loop, you can find more detailed answer [here](http://stackoverflow.com/a/42036327/7465829) – Jack Brown May 07 '17 at 08:44
  • Thank you Tanaike, it worked. How can i mark your reply as the solution for this question? It does not show the button. – Din May 07 '17 at 08:54
  • @Din Uzakbayev Thank you for your concern. I posted my answer just now. You can accept as a solved answer. Thank you again. – Tanaike May 07 '17 at 11:44

1 Answers1

0

How about a following modification for the for loop.

From :

for (var i=0; i<=rawData.length; i++) {

To :

for (var i=0; i<=rawData.length - 1; i++) {

or

for (var i=0; i<rawData.length; i++) {

Index of Array is from 0 to Array.length - 1. So for (var i=0; i<=rawData.length; i++) { occurs an error at rawData.length.

As another expression, you can use

for (var i in rawData) {

In this case, you can also retrieve elements by rawData[i][3].

Tanaike
  • 181,128
  • 11
  • 97
  • 165