在嵌套的每个循环中无法访问顶级变量。 JavaScript的?

时间:2017-11-01 17:55:52

标签: javascript

使用此代码:

addDefaultComments() {
    $('.image').each((index, image) => {
      Comment.defaults.forEach((comment) => {
        debugger;
        $('#images').find(`ul[data-id=${imageId}] ul#comments-${imageId}`).append(`<li>${comment.commentContent}</li>\n`);
      })
    })
  }

在这个debugger语句中,我不应该访问图像和索引吗?当我打电话给他们时,它说他们没有被定义。这不奇怪吗?

证明发生了奇怪的事情:

enter image description here

enter image description here

1 个答案:

答案 0 :(得分:3)

  

在此调试器声明中,我不应该有权访问imageindex吗?

是的,你应该;并且你这样做 - 除非他们因为你没有使用它们而得到优化。这就是这里发生的事情。 Chrome正在积极优化该功能,因为您实际上并未在任何地方使用 indeximage。如果你使用它们,它们就在那里:

Proof that it works fine with arrow functions in an up-to-date version of Chrome

(如果你想玩它,那就是小提琴:http://jsfiddle.net/Lbe2pue0/

如果使用它们,它们就不在那里:

Proof they aren't there if you don't use them

(这就是小提琴:http://jsfiddle.net/Lbe2pue0/1/

(我认为Chrome在箭头功能中执行此优化非常有趣,但在function函数中没有...)