带有ES6箭头函数的jQuery .each()函数

我有这个ES6代码,在用Babel编译它到ES5之后, this内部.each的回调变得undefined 。 我该如何解决这个问题?

 let mediaBoxes = $(".now-thumbnail"); let titles = []; mediaBoxes.each(() => { let obj = { index: i, title: $(this).find(".now-thumbnail-bottomtext").text().trim() }; titles.push(obj); }); 

我的解决方案是根本不使用this ,而是使用传递给回调函数的变量。 第一个是索引,第二个是DOM元素本身。

  let mediaBoxes = $(".now-thumbnail"); let titles = []; mediaBoxes.each((index, element) => { let obj = { index: index, title: $(element).find(".now-thumbnail-bottomtext").text().trim() }; titles.push(obj); }); 

那是因为箭头函数的平均值不同。

这个

箭头函数捕获封闭上下文的this值,

each()函数将元素作为回调的第二个参数传递。

但是更合适的解决方案是使用.map()而不是每个()

 let mediaBoxes = $(".now-thumbnail"); let titles = mediaBoxes.map((i, el) => { return { index: i, title: $(el).find(".now-thumbnail-bottomtext").text().trim() }; }).get();