gpt4 book ai didi

javascript - 为什么 Array.prototype.reduce() 不将空对象字面量作为初始值?

转载 作者:行者123 更新时间:2023-11-30 10:03:00 25 4
gpt4 key购买 nike

我正在学习 NodeJS 推荐的 functional-javascript-workshop 教程(练习 6)。

我写了下面的简单代码,它应该计算数组中每个单词的出现次数,并将结果作为一个对象返回,其中每个键值对是 word: # of occurrences.

function countWords (inputWords) {
return inputWords.reduce(function (obj, current) {
obj[current] = typeof obj[current] === 'number' ? obj[current] + 1 : 1;
}, {});
}

如果我使用 countWords(['bob']) 运行它,我会得到错误:Uncaught TypeError: Cannot read property 'bob' of undefined。 carat指向第三行的typeof obj[current]表达式。

如果我在 reduce() 函数的第一行 console.log(obj),它会输出 Object {}。如果我在第一行 console.log(typeof obj),它会输出 object。那么为什么它认为它是未定义的呢?不允许使用这种语法吗?

最佳答案

函数的返回值将用作 inputWords 中下一个值的 obj 参数。由于您没有显式返回任何内容,因此 JavaScript 返回 undefined。这就是您收到错误的原因。要解决这个问题,您需要返回 obj

function countWords (inputWords) {
return inputWords.reduce(function (obj, current) {
obj[current] = typeof obj[current] === 'number' ? obj.current + 1 : 1;
return obj; // Return the accumulated value
}, {});
}

无论如何,考虑到未知键默认返回 undefined 的事实,您的逻辑可以稍微简化,就像这样

function countWords(inputWords) {
return inputWords.reduce(function (obj, current) {
obj[current] = (obj[current] || 0) + 1;
return obj; // Return the accumulated value
}, {});
}

关于javascript - 为什么 Array.prototype.reduce() 不将空对象字面量作为初始值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30628521/

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