javascript - 函数返回 [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函数返回正确的集?我将不胜感激找到该问题的答案的任何帮助。
解决方案
这种行为与输出的位置无关,而与输出的格式无关。
你有这些陈述:
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)
将渲染留给console
API,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
方法会生成一个逗号分隔的值列表,它解释了您提到的输出。
推荐阅读
- r - 是否有一个基本的 R 函数来动态排序类似于 dplyr Everything() 的 data.frame 列?
- ldap - Salt ldap.managed 'Tuple_to_LDAPMod' 'expected a tuple' 问题
- php - 正则表达式搜索和替换数组键
- reactjs - 由 axios 取消令牌引起的 react useEffect hook 无限循环 [react-hooks/exhaustive-deps]
- sql - 排名值以确定最高值
- reactjs - 如何使用 Reactjs 中的 MaterialTable 通过 REST 调用实现内联添加新行、编辑和删除行
- java - 如何检查某个字符是否出现在字符串中?
- android - 在 NativeScript 6 Angular 中无法获得透明的 WebView(设置 backgroundColor 透明和 layertype 软件)
- python - 使用 flask-sqlalchemy 动态链接到数据库
- javascript - Firebase 云功能,带有对外部 api 的基本身份验证的获取请求