-1

i have a object called numObj and I created a numArrary containing an array of numObj objects. When I try to use foreach to call its inner members, it turns out unaccessable. Why's that?

   var numObj = function (num) {
        return {
            num:num
        }
    }
    var numArray = [];
    for (var i = 0; i < 3; i++) {
        numArray[i] = numObj(i);
    }
    numArray.forEach(
        function () {
            alert(this.num); //undefined
        }
    );

Moreover when I get deeper level of inner objects, I lose my intellisense in VS. Any idea?

Hoy Cheung
  • 1,552
  • 3
  • 19
  • 36
  • i this really javascript? Dont you want to use a `for(numObj in numArray)` form? – shishirmk Apr 19 '13 at 07:19
  • 1
    @shishirmk: Yes, it's really JavaScript. – T.J. Crowder Apr 19 '13 at 07:20
  • @ user: *"i have a object called numObj"* You do, yes, although most people would have called it a function. (It's *also* an object, because JavaScript functions are objects, but...) – T.J. Crowder Apr 19 '13 at 07:21
  • @T.J.Crowder Thanks just tried it in CDT console. Dint know about this format at all.. – shishirmk Apr 19 '13 at 07:22
  • @shishirmk: No worries. :-) *"Dint know about this format..."* Well, nothing's changed *syntactically* (the OP just has a slightly unusual approach to line breaks, but quite a clean and readable one). `forEach` is just a function on arrays, added by ES5. – T.J. Crowder Apr 19 '13 at 07:24

2 Answers2

4

The entry is passed as the first argument to the forEach iterator, so:

numArray.forEach(
    function (obj) {    // Declare the argument
        alert(obj.num); // Use it
    }
);

forEach doesn't use this for the entry (as, for instance, jQuery's similar function does).

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • Thanks Crowder, How about for ( a in b) expression? – Hoy Cheung Apr 19 '13 at 07:26
  • 1
    @user1978421: The `for-in` loop iterates over the enumerable properties of an object. It's not usually the best way to loop through an array's contents, for various reasons. More in [this other answer on SO](http://stackoverflow.com/questions/9329446/for-each-in-a-array-how-to-do-that-in-javascript/9329476#9329476) and [this post on my blog](http://blog.niftysnippets.org/2010/11/myths-and-realities-of-forin.html). – T.J. Crowder Apr 19 '13 at 07:34
0

Try this:

  var numArray = [{1:1},{2:2}];


   numArray.forEach(function(value,index){
         console.log(value,index,this);//{1:1},0 window
   });

this - refers to window

Fiddle

karthick
  • 5,998
  • 12
  • 52
  • 90