Cheerio各循环不提前爆发

Cheerio each loop does not break out early

在 Cheerio/Jquery documentation 中指出,return false 应该提前中断每个循环。

我有以下代码:

"use strict";
let cheerio = require('cheerio');
let $ = cheerio.load('<a href="www.test.com"></a><a href="www.test.com"></a>');

$('a').each(function(index,value){
  console.log(index);
  return false;
});

在我看来,它应该向控制台打印 0,但它打印了 0 和 1。我错过了什么?

代码没问题。如果您查看 cheerio 的源代码,您会发现如果 return false,循环将无法继续。

https://github.com/cheeriojs/cheerio/blob/master/lib/api/traversing.js#L298

exports.each = function(fn) {
  var i = 0, len = this.length;
  while (i < len && fn.call(this[i], i, this[i]) !== false) ++i;
  return this;
};