Random substring error? “TypeError: Cannot find function substring in object…”

ⅰ亾dé卋堺 提交于 2021-02-08 06:24:17

问题


The error is:

TypeError: Cannot find function substring in object

The code loops through 10 values, checking for the first character being a number.

function TypeErrorMystery() {

  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var s = ss.getActiveSheet();

  //loop from cell 1-10
  for (var i = 0; i < 10; i++) {
    var range = s.getRange(i + 1, 1)
    var substring1 = range.getValue().substring(0, 1);
      //if first character in cell is #
      if (substring1 === "#" ) {
         //write over it with "success"
         range.setValue("success");
      }
   };
}

The exact error is:

TypeError: Cannot find function substring in object 3. (line 9, file "Code"),

where line 9 is:

var substring1 = range.getValue().substring(0, 1);

回答1:


The value in the cell is the number 3. The substring() method throws an error when being applied to a number. You should check the type of value that is returned.

if (typeof thisCellValue === 'number') {continue;};//Skip over numbers

Entire Code:

function TypeErrorMystery() {

  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var s = ss.getActiveSheet();
  var range,
      substring1,
      thisCellValue;

  //loop from cell 1-10
  for (var i = 0; i < 10; i++) {
    range = s.getRange(i + 1, 1)
    thisCellValue = range.getValue();
    Logger.log('typeof thisCellValue: ' + typeof thisCellValue);

    if (typeof thisCellValue === 'number') {continue;};

    substring1 = thisCellValue.substring(0, 1);

    //if first character in cell is #
    if (substring1 === "#" ) {
      //write over it with "success"
      range.setValue("success");
    }
  };
};


来源:https://stackoverflow.com/questions/35256409/random-substring-error-typeerror-cannot-find-function-substring-in-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!