如何测试两个NodeList的相等性?

ESR*_*ESR 3 javascript object nodelist

假设我有一个自定义函数,我希望它将返回一个NodeList:

getNodeList('foo');

我希望此NodeList与从以下返回的NodeList相同:

document.querySelectorAll('.foo');

如何检查我的期望是正确的?

这样做不起作用:

getNodeList('foo') == document.querySelectorAll('.foo')
Run Code Online (Sandbox Code Playgroud)

我敢肯定有一个很好的技术原因为什么它不起作用,因为它document.querySelectorAll('.foo') == document.querySelectorAll('.foo')也不起作用,所以我认为这是可以预期的。

如何测试两个NodeList是否包含相同的HTML节点?

mau*_*oc8 5

数组相等是通过引用而不是内容来实现的。

let a = [1, 2, 3], b = [1, 2, 3]
let c = a
a == c // => true, since both refer to `a`
a == b // => false
Run Code Online (Sandbox Code Playgroud)

如果要比较两个类似数组的对象,则必须按索引进行比较。

function eq(A, B) {
  if (A.length !== B.length) return false;
  for (let i = 0; i < A.length; i++) {
    if (A[i] !== B[i]) return false;
  }
  return true;
}
Run Code Online (Sandbox Code Playgroud)

当然,您总是可以使用一些函数式编程魔术:

let arrayEq = (A, B) => A.length === B.length && A.every((e, i) => e === B[i]);
Run Code Online (Sandbox Code Playgroud)

但是,仅当A是一个数组(而不是NodeList)时,它才起作用。


然后尝试

eq(getNodeList('foo'), document.querySelectorAll('.foo'))
Run Code Online (Sandbox Code Playgroud)

要么

arrayEq(Array.from(getNodeList('foo'), document.querySelectorAll('.foo'))
Run Code Online (Sandbox Code Playgroud)