gpt4 book ai didi

javascript - 对象比较函数,看不懂这个例子

转载 作者:行者123 更新时间:2023-11-29 21:42:00 24 4
gpt4 key购买 nike

以下示例摘自 Eloquent Javascript 第 4 章末尾的练习。 .

function deepEqual(a, b) {
if (a === b) return true;

if (a == null || typeof a != "object" ||
b == null || typeof b != "object")
return false;

var propsInA = 0, propsInB = 0;

for (var prop in a)
propsInA += 1;

for (var prop in b) {
propsInB += 1;
if (!(prop in a) || !deepEqual(a[prop], b[prop]))
return false;
}

return propsInA == propsInB;
}

大部分功能对我来说都很容易理解,但有一部分我不太确定发生了什么:

 for (var prop in b) {
propsInB += 1;
if (!(prop in a) || !deepEqual(a[prop], b[prop]))
return false;
}

一个 for 循环遍历提供的对象“b”中的属性,每次递增 propsInB 的值,然后我真的不明白为什么 if 语句的条件是它们的样子。

如有任何解释,我将不胜感激。

最佳答案

好吧,让我们分析一下..

for (var prop in b) {
propsInB += 1; // Increment to
if (
!(prop in a) || // exists in a???
!deepEqual(a[prop], b[prop])) // !! -> this is the point where recursion is happaning
return false;
}

这会检查该属性是否存在于 a 中。

   !(prop in a)  

这是递归发生的地方..

!deepEqual(a[prop], b[prop]))

想象一下递归,就像您在文件夹结构中寻找最深的文档:/home/me/stuff/cool-stuff/games/..

你不知道结构,但你必须找到最深的文件,你会用递归来完成。

伪代码:

  goDeeper(folder) {
childFolders = findAllFolderInFolder(folder);
if (!childFolders) {
alert('found the deepest Folder: ' + folder);
return;
} else
childFolders.forEach(goDeeper); // Call goDeeper for each folder in this folder...
}

goDeeper('/'); // It will go through all the filesystem, and each time it finds an end it will alert('...');

所以这个伪代码会走进每个文件夹并尝试越来越深..

关于javascript - 对象比较函数,看不懂这个例子,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32467432/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com