【发布时间】:2021-01-06 04:35:19
【问题描述】:
我希望每个人都身体健康,身体健康。
最近,我一直在使用应用程序脚本和学习 Google Docs 超链接。我试图获取所有超链接并对其进行编辑,为此我从post 中找到了一个惊人的代码。我已经多次阅读代码,现在我对它的工作原理有了很好的理解。
我的困惑
我的困惑是这段代码中发生的递归过程,虽然我熟悉递归函数的概念,但是当我尝试修改代码以仅从文档中获取第一个超链接时,我无法理解如果没有它我怎么能做到这一点打破递归函数。
这是我正在尝试的代码;
/**
* Get an array of all LinkUrls in the document. The function is
* recursive, and if no element is provided, it will default to
* the active document's Body element.
*
* @param {Element} element The document element to operate on.
* .
* @returns {Array} Array of objects, vis
* {element,
* startOffset,
* endOffsetInclusive,
* url}
*/
function getAllLinks(element) {
var links = [];
element = element || DocumentApp.getActiveDocument().getBody();
if (element.getType() === DocumentApp.ElementType.TEXT) {
var textObj = element.editAsText();
var text = element.getText();
var inUrl = false;
for (var ch=0; ch < text.length; ch++) {
var url = textObj.getLinkUrl(ch);
if (url != null) {
if (!inUrl) {
// We are now!
inUrl = true;
var curUrl = {};
curUrl.element = element;
curUrl.url = String( url ); // grab a copy
curUrl.startOffset = ch;
}
else {
curUrl.endOffsetInclusive = ch;
}
}
else {
if (inUrl) {
// Not any more, we're not.
inUrl = false;
links.push(curUrl); // add to links
curUrl = {};
}
}
}
if (inUrl) {
// in case the link ends on the same char that the element does
links.push(curUrl);
}
}
else {
var numChildren = element.getNumChildren();
for (var i=0; i<numChildren; i++) {
links = links.concat(getAllLinks(element.getChild(i)));
}
}
return links;
}
我尝试添加
if (links.length > 0){
return links;
}
但它不会停止函数,因为它是递归的,它会返回到之前的调用并继续运行。
这是我正在处理的测试文档及其脚本。
https://docs.google.com/document/d/1eRvnR2NCdsO94C5nqly4nRXCttNziGhwgR99jElcJ_I/edit?usp=sharing
希望您能理解我要传达的内容,感谢您查看我的帖子。保持快乐:D
【问题讨论】:
标签: google-apps-script hyperlink google-docs