【发布时间】:2022-01-07 03:29:48
【问题描述】:
我有一个嵌套对象,它具有不同类型的属性,包括字符串、对象和数组。我使用递归的方法来计算对象中键的总数(从key1到key9),但未能得到正确的解决方案。下面是我的代码示例。
const data = {
key1: '1',
key2: '2',
key3: { key4: '4' },
key5: [
{
key6: '6',
key7: '7',
},
{
key8: '8',
key9: '9',
}
]
}
const countKeys = (data) => {
let count = 0;
const helper = (data) => {
for (let value of Object.values(data)) {
if (typeof value === 'object') {
helper(value);
}
// this line is problematic as it counts each object in the array as key.
if (!Array.isArray(value)) count++;
}
}
helper(data)
return count;
}
console.log(countKeys(data)) // 10, correct answer is 9
我尝试了好几个小时,但无法找到解决方案。谁能解释一下我在这里缺少什么并应该添加以使其正常工作?
【问题讨论】:
-
嗨,也许用
Object.keys -
你到底是如何达到 10 的?如果您神奇地不计算数组索引,我会看到 9,否则为 11。
-
只是想知道您到底想计算什么? 9 计算从
key1到key9的所有项目 -
@jspacal 我认为当我们到达具有数组属性的“key5”时,Object.keys 不会起作用?
-
@ASDFGerte 实际上有一个错字。正确答案应该是 9,但我得到了 10。
标签: javascript arrays object recursion nested