You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Google Apps Script中判断Google Docs的两个子对象是否相同?

如何判断两次调用parent.getChild()获取的是同一个子对象?

在Google Apps Script的Document Service中,每次调用getChild()都会返回一个全新的对象实例,所以直接用===进行全等比较会返回false,这是框架的设计机制导致的,并非安全限制。

要判断两次获取的是否为同一个文档元素,最可靠的方式是使用元素的getId()方法——每个文档元素都拥有唯一且持久的ID,通过比较ID即可确认是否为同一元素。

修改后的验证代码:

function example() {
  let doc = DocumentApp.getActiveDocument();
  let body = doc.getBody();
  let child1 = body.getChild(0);
  let child2 = body.getChild(0);
  // 比较元素ID
  console.log(`child1.getId() === child2.getId() is ${child1.getId() === child2.getId()}`);
}

输出:

child1.getId() === child2.getId() is true

另外,如果你只是临时判断(比如元素位置不会变动的场景),也可以通过比较元素在父容器中的索引和类型来辅助验证,但getId()是最稳定的方案,即使元素在文档中被移动,ID也不会改变。

内容的提问来源于stack exchange,提问作者Adrian

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.15 00:32:02