如何比较 Google Docs 的 Google Apps 脚本中的两个子对象?

问题描述 投票:0回答:1

我对此感到非常惊讶。

parent.getChild(0) !== parent.getChild(0)
。 🤔😢🤬

那么我该如何通过两次不同的调用

parent.getChild()
来确定一个孩子是否与另一个孩子相同?

最小可重现示例:

function example() {
  let doc = DocumentApp.getActiveDocument();
  let body = doc.getBody();
  let child1 = doc.getChild(0);
  let child2 = doc.getChild(0);
  console.log(`child1 === child2 is ${child1 === child2}`);
}
google-apps-script google-docs
1个回答
0
投票

因此,为了确定两个子对象是否相同,我生成了从子对象到文档根的路径并比较了它们。

/**
 * Get the path to an object for a child Element.  This is needed because there
 * doesn't seem to be a way to directly compare two objects directly.  Comparing
 * the path is the next best thing.
 * 
 *   I.e. parent = child.getParent();
 *        parent.getChild(parent.getChildIndex(child)) !== child  // WTF?!?!?
 * 
 * @param {Element}
 *   Must be a child element.
 * 
 * @returns {Integer[]}
 *   This is array with the leaf at index 0 and the root at the end.  This value
 *   is unique to the element in a document.  Use equivalent() to test if two
 *   elements are the same.
 */
function getDocObjPath(element) {
  if (!element.getParent) {
    throw Error(`element (${formatValue(element)}) doesn't have a getParent function.`);
  }
  let docObjPath = [];
  while (element.getParent) {
    const parent = element.getParent();
    if (parent === null) {
      log('parent is null', LOG_LEVEL.INFO);
      break;
    }
    if (parent.getChildIndex) {
      const childIndex = parent.getChildIndex(element);
      docObjPath.push(childIndex);
      element = parent;
    }
  }
  return docObjPath;
}
/**
 * A simplified version of my equivalent function.
 *
 * @param {Integer[]} lhs
 *   Left hand side of the test.
 * @param {Integer[]} rhs
 *   Right hand side of the test.
 *
 * @returns {boolean}
 *   Returns true if the arrays have the same content, false otherwise.
 */
function equivalent(lhs, rhs) {
  return lhs.length === rhs.length && lhs.every((v, i) => v === rhs[i]);
}

测试:

function example() {
  let doc = DocumentApp.getActiveDocument();
  let body = doc.getBody();
  let child1Path = getDocObjPath(doc.getChild(0));
  let child2Path = getDocObjPath(doc.getChild(0));
  console.log(`child1Path same as child2Path is ${equivalent(child1Path, child2Path)}`);
}

输出:

child1Path same as child2Path is true
最新问题
© www.soinside.com 2019 - 2025. All rights reserved.