我正在从工作表中获取边框值并在 Gmail 中创建一个 HTML 表格。我是 Javascript(谷歌脚本)的新手,正在努力优化代码。
我正在使用高级工作表属性来获取每个单元格的边框值。如果边框不存在,则值未定义,而不是返回“无”。因此,使用 try-catch 将边框值设置为“无”。
我读了一些博客,它们说 try-catch 应该最少使用,它会减慢代码速度。有没有办法改进此代码,因为我对每个单元格的每个边框(顶部、左侧、右侧和底部)使用 try-catch?
没有 try-catch 返回的错误是“无法从未定义中读取属性“0.0””。
//Creating an array of border values by assigning the range values
var aBorderValues = JSON.parse(JSON.stringify(Sheets.Spreadsheets.get(spreadsheetID, {ranges: borderRange, fields: "sheets/data/rowData/values/userEnteredFormat/borders"})));
// Getting the top border style
try
{
var topBorder =aBorderValues.sheets[0].data[0].rowData[i].values[j].userEnteredFormat.borders.top.style;
}
catch (etop)
{
topBorder = "none";
}
最佳答案
您可以在 lodash 中编写类似 get
的内容,并以字符串和/或数字数组的形式提供您要访问的属性的路径:
function get (object, path, defaultValue) {
return object === undefined //object at current path is undefined
? defaultValue //return default value
: path.length === 0 //no more items in path
? object //return value at completed path (path.length === 0)
: object[path[0]] === undefined //go one level deeper
? defaultValue //there is nothing one level deeper, return default
: get(object[path[0]], path.slice(1), defaultValue); //recursively call itself
}
const test = [{ name: 'hi' }];
console.log(get(test, [0, 'name']));
console.log(get(test, [1, 'name'], 'default value'));
console.log(
get(undefined, [1, 'name'], 'other default value'),
);
//index of array does not have to be a number:
console.log(get(test, ['0', 'name']));
关于javascript - 从 Google Spreadsheet 获取边框值时,如何避免对未定义的值进行多次 try catch (通过使用 if/else 或其他方式)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53718748/