首页 > 解决方案 > 函数返回 [object Set] 而不是实际的 Set

问题描述

我有一个功能

function recursiveDivisionWrap(width, height, colStart, colEnd, rowStart, rowEnd)

我有一个空集

let blockedNodes = new Set();

在这个函数里面我有另一个递归函数

function recursiveDivision(width, height, colStart, colEnd, rowStart, rowEnd)

在每次调用recursiveDivision函数时,我都会通过添加值来更新blockNodes集:

for (let i = colStart; i < colEnd; i++) {
        blockedNodes.add(`c${i}r${wallStart}`);
      }

如果我在recursiveDivision函数中设置了 console.log blockedNodes,我会得到想要的结果,例如:

Set(43) {'c0r7', 'c1r7', 'c2r7', 'c3r7', 'c4r7', …}

但是,当我在 recursiveDivisionWrap 中设置 console.logblockedNodes不是在recursiveDivision中时,我会得到逗号分隔的对象:

c0r7,c1r7,c2r7,c3r7,c4r7,c5r7,c6r7,c7r7,c8r7,c9r7,c9r0,c9r1,c9r2,c9r3,c9r4,c9r5,c9r6,c8r0,c8r1,c8r2,c8r3,c8r4,c8r5,c8r6,c3r0,c3r1,c3r2,c3r3,c3r4,c3r5,c3r6,c4r6,c5r6,c6r6,c7r6,c4r1,c5r1,c6r1,c7r1,c4r5,c5r5,c6r5,c7r5

我也尝试过使用数组,结果是一样的。

Set(43) {'c0r7', 'c1r7', 'c2r7', 'c3r7', 'c4r7', …}如果在recursiveDivision函数之外和 recursiveDivisionWrap 内部定义blockedNodes集,为什么它不返回,为什么内部recursiveDivision函数返回正确的集?我将不胜感激找到该问题的答案的任何帮助。

标签: javascriptfunctionobjectset

解决方案


这种行为与输出的位置无关,而与输出的格式无关。

你有这些陈述:

console.log(blockedNodes);

和:

console.log(`Is this a set? ${blockedNodes}`);

和:

let ecie = Array.from(blockedNodes);
console.log(`Is this an array? ${ecie}`)

他们不做同样的事情。

console.log(blockedNodes)将渲染留给consoleAPI,API 可能会提供额外的信息,例如对象的构造函数的名称(Set在这种情况下)、此集合具有的项目数等。它甚至可以添加用户界面控件来展开/折叠集合的内容和潜在的嵌套数据结构。

console.log(`Is this a set? ${blockedNodes}`)将隐式调用blockedNodes.toString()以生成字符串。除非toString已被覆盖,否则将呈现为[object Set],因此总输出将是“这是一个集合吗?[对象集合]”。

console.log(`Is this an array? ${ecie}`)也将调用该toString方法,但这次 on ecie,它是一个数组(因为它是Array.from返回的)。数组上的toString方法会生成一个逗号分隔的值列表,它解释了您提到的输出。


推荐阅读