使用的typeError:使用发电机函数时元素是不确定的
我有以下JavaScript片段:
/**
* Returns the maximal element in the `iterable` as calculated by the given function
* @param {Iterable} iterable - iterable to find the maximal element in
* @param {function} fn - function to calculate the maximal element
*
* @returns {any} - maximal element in the `iterable`
*/
function maxBy(iterable, fn) {
let maximalElement = iterable[0];
for (let element of iterable) {
if (fn(element) > fn(maximalElement)) {
maximalElement = element;
}
}
return maximalElement;
}
// example generator function
generator = function* () {
yield [3,4]
yield [4,6]
}
maxBy(generator(), element => element[1])
当我在浏览器控制台中运行此程序时,我会得到unduck typeError:element是未定义的
错误,我似乎无法发现代码中的错误在哪里。
I have the following javascript snippet:
/**
* Returns the maximal element in the `iterable` as calculated by the given function
* @param {Iterable} iterable - iterable to find the maximal element in
* @param {function} fn - function to calculate the maximal element
*
* @returns {any} - maximal element in the `iterable`
*/
function maxBy(iterable, fn) {
let maximalElement = iterable[0];
for (let element of iterable) {
if (fn(element) > fn(maximalElement)) {
maximalElement = element;
}
}
return maximalElement;
}
// example generator function
generator = function* () {
yield [3,4]
yield [4,6]
}
maxBy(generator(), element => element[1])
When I run this in browser console, I get Uncaught TypeError: element is undefined
error and I can't seem to spot where's the error in my code.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您不能使用
iToble [0]
访问发电机中的第一个元素。您需要获取迭代器并进行迭代:或者,只需使用
初始化undefined
maximalelemt
,如果iTable是空的,这可能会发生这种情况:You cannot use
iterable[0]
to access the first element in a generator. You'll need to get the iterator and iterate it:Alternatively, just initialise
maximalElement
withundefined
, this might happen anyway if the iterable is empty: