gpt4 book ai didi

javascript - 随机子串错误? "TypeError: Cannot find function substring in object..."

转载 作者:行者123 更新时间:2023-11-29 19:16:06 25 4
gpt4 key购买 nike

错误是:

类型错误:无法在对象中找到函数子字符串

代码循环遍历 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");
}
};
}

准确的错误是:

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

第 9 行是:

var substring1 = range.getValue().substring(0, 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");
}
};
};

关于javascript - 随机子串错误? "TypeError: Cannot find function substring in object...",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35256409/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com