【问题标题】:Random substring error? "TypeError: Cannot find function substring in object..."随机子串错误? “TypeError:在对象中找不到函数子字符串......”
【发布时间】:2016-02-07 17:07:07
【问题描述】:

错误是:

TypeError:在对象中找不到函数子字符串

代码循环遍历 10 个值,检查第一个字符是否为数字。

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");
      }
   };
}

确切的错误是:

TypeError:在对象 3 中找不到函数子字符串。(第 9 行,文件“代码”)

第 9 行在哪里:

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

【问题讨论】:

    标签: javascript google-apps-script google-sheets google-apps


    【解决方案1】:

    单元格中的值是数字 3。substring() 方法在应用于数字时会引发错误。您应该检查返回的值的类型。

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

    完整代码:

    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");
        }
      };
    };
    

    【讨论】:

    • 子字符串案例关闭!那东西已经咬了我好几天了……谢谢@Sandy
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-03-11
    • 2011-04-06
    • 1970-01-01
    • 1970-01-01
    • 2015-04-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多