Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeError: Cannot read property "0" from undefined

I'm getting a very weird undefined error:

function login(name,pass) {
  var blob = Utilities.newBlob(pass);
  var passwordencode = Utilities.base64Encode(blob.getBytes());
  var ss = SpreadsheetApp.openById("");
  var sheet = ss.getActiveSheet();
  var data = sheet.getDataRange().getValues();
  var i=1;
  while (name != data[i][0]){
    Logger.log(data[i][0]);
    i++;
  }
  if (passwordencode == data[i][1]){
    UserProperties.setProperties({
      "name" :name,
      "pass" : passwordencode
      });
    Logger.log("You are logged in");
  }
  else if (passwordencode != data[i][1]) {
    Logger.log("You are not logged in");
    UserProperties.setProperties({
      "name" : "",
      "pass" : ""
      });
  }
}

using googlescript. The one that's undefined is the while statement where while(name != data[i][0]) claiming that you cannot read property "0" from undefined. What's weird about this, If I remove the data[i][0] in the while statement, it still works in the logger.log. And everywhere else. What the heck is going on?

EDIT: If I change the while to a if statement it also works.

like image 483
IGratch Avatar asked Sep 22 '13 18:09

IGratch


People also ask

How do you fix TypeError Cannot read property of undefined?

The “cannot read property of undefined” error occurs when you attempt to access a property or method of a variable that is undefined . You can fix it by adding an undefined check on the variable before accessing it.

Can not read the property 0 of undefined?

To resolve your TypeError: Cannot read properties of undefined (reading '0') , go through these steps: Ensure you are using the correct variable. Perform a simple check on your variable before using it to make sure it is not undefined. Create a default value for the variable to use if it does happen to be undefined.

What is TypeError Cannot read property of undefined?

Causes for TypeError: Cannot Read Property of Undefined In short, the value is not assigned. In JavaScript, properties or functions are Objects, but undefined is not an object type. If you call the function or property on such variable, you get the error in console TypeError: Cannot read undefined properties.

Can not set properties of undefined?

The "Cannot set properties of undefined" error occurs when setting a property on an undefined value. To solve the error, conditionally check if the value is of the expected type (object or array) or has to be initialized before setting the property on it.


1 Answers

The while increments the i. So you get:

data[1][0]
data[2][0]
data[3][0]
...

It looks like name doesn't match any of the the elements of data. So, the while still increments and you reach the end of the array. I'll suggest to use for loop.

like image 144
Krasimir Avatar answered Oct 11 '22 00:10

Krasimir