如何在Google Apps Script中根据数组长度动态构建SpreadsheetApp链式调用?
在Google Apps Script中动态构建链式调用的setTextStyle方法
完全可以实现这种动态链式调用。因为SpreadsheetApp.newRichTextValue()返回的是RichTextValueBuilder实例,而该实例的所有链式方法(比如setText()、setTextStyle())都会返回自身,所以我们可以通过遍历参数数组的方式,动态添加任意次数的setTextStyle()调用。
实现代码示例
function createRichText(a, arr, bold) { // 初始化RichTextValueBuilder实例 let builder = SpreadsheetApp.newRichTextValue().setText(a); // 遍历参数数组,动态调用setTextStyle arr.forEach(params => { builder.setTextStyle(params[0], params[1], bold); }); // 构建最终的RichTextValue return builder.build(); }
效果验证
- 当
arr长度为1时,函数内部执行逻辑等价于:
let builder = SpreadsheetApp.newRichTextValue().setText(a); builder.setTextStyle(arr[0][0], arr[0][1], bold); return builder.build();
- 当
arr长度为2时,执行逻辑等价于:
let builder = SpreadsheetApp.newRichTextValue().setText(a); builder.setTextStyle(arr[0][0], arr[0][1], bold); builder.setTextStyle(arr[1][0], arr[1][1], bold); return builder.build();
这种方式完全适配数组长度的变化,不管数组有多少组参数,都能自动对应调用多少次setTextStyle()方法。
内容的提问来源于stack exchange,提问作者golddave
相关产品推荐
相关产品推荐

