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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/36638002/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 19:20:36  来源:igfitidea点击:

jQuery .each() function with ES6 arrow functions

javascriptjqueryecmascript-6babeljs

提问by Tekeste Kidanu

I have this ES6 code, after I compile it with Babel to ES5 the thisinside .each's call back becomes undefined. How do I fix this problem?

我有这个 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);
});

回答by Tekeste Kidanu

My solution is to not use thisat all, but use the variables that are passed to the callback function. The first one is the index and the second one gives you the DOM element itself.

我的解决方案是根本不使用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);
 });

回答by Arun P Johny

That is because the mean of thisis not the same in arrow functions.

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

this

这个

Arrow functions capture the this value of the enclosing context,

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

The each()function passes the element as the second argument to the callback.

每个()函数传递元件作为第二个参数回调。

But a more appropriate solution for you will be to also use .map()instead of each()

但更适合您的解决方案是也使用.map()而不是each()

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