-1

All:

[UPDATE problem solved] The problem I have here is: so if I use "in", the func is the index number while using "of" the func is the function. More detail refer to Variables and scoping in ECMAScript 6

This is my first hour of ES6 study, I wonder why I can not use syntax like:

for(func in funcs) { }

In:

  "use strict";

  var funcs = [];
  for(let i=0; i<10; i++){
    funcs.push(function(){
      console.log(i); 
    });
  }

  let func;
  for(func in funcs){
    func();
  }

It always reports:

Uncaught TypeError: func is not a function
Kuan
  • 11,149
  • 23
  • 93
  • 201

1 Answers1

1

for... in iterates over object keys. It's been in JavaScript since day one.

I think you are confusing it with for... of, which is an ES6 feature for looping over iterable objects including Arrays.

for(let func of funcs){
  func();
}

Babel.js REPL

joews
  • 29,767
  • 10
  • 79
  • 91
  • Thanks, this is new knowledge to me! I will accept this after 7 minutes – Kuan Oct 29 '15 at 21:03
  • 1
    Thanks, now I am clear the usage, so if I use "in", the func is the index number while using "of" the func is the function. – Kuan Oct 29 '15 at 21:08
  • 2
    Yes, and there are some [good reasons](http://stackoverflow.com/questions/500504/why-is-using-for-in-with-array-iteration-such-a-bad-idea) that you shouldn't use it for Arrays. `for... of` doesn't have the same problems. – joews Oct 29 '15 at 21:09
  • Another confuse about this is: I read that "let" can prevent duplicated declaration of same variable, but if I put the "let" inside the for, it still work, does that means each round of loop, ES6 will create a new block to hold specific func variable in that round? – Kuan Oct 29 '15 at 21:10
  • Thanks, so even the let inside the for, it only seems like declare func each loop from the format while actually it is only declared func once and keep reusing it and only difference comparing with declaration outside for loop is the place that func variable lives? But if so, this confuse me so much: why each func can have their own "i"? – Kuan Oct 29 '15 at 21:19
  • Yeah, that is my confuse lies. Since every loop share the same i ( rather than another i ), why in the fun, it can show according i(0,1,2,3..9) – Kuan Oct 29 '15 at 22:12
  • 1
    I've deleted comments as I think they were a little confusing - this article should clarify :-) http://www.2ality.com/2015/02/es6-scoping.html. – joews Oct 29 '15 at 22:22
  • Thanks I will read this. – Kuan Oct 29 '15 at 22:34
  • I read that post, so if I use "let" VS "var", it will affect how JS engine treat each loop's storage space creation( if "let", then there will be multiple storage space created for specific "i" and the function defined in it ), right? – Kuan Oct 29 '15 at 22:48
  • I don't know about storage space (the spec doesn't say anything about _how_ to use memory), but you can think of it as a separately bound `let` for each iteration. – joews Oct 29 '15 at 22:50