2

Again, seems like a brain fart on my side. Trying to make sample operation by looping through all of the objects in array and changing observable property on those objects:

var sss = vm.tripData();
                for (var sh2 in sss) {
                    sh2.isVisible(false);
                }

sss contains array of objects, I can see it in VS2012 locals - this is what I need. I declared sss just to see what I'm trying to enumerate. Inside loop first sh2 contains string "0" Why? I guess it's some javascript thing (I'm from c# background).. I expect sh2 to be my object.

EDIT:

This is what I see in debugger:

sss object

sh2 string

katit
  • 17,375
  • 35
  • 128
  • 256
  • Have you tried debugging and see what `sss` contains? could it be that it actually contains strings and not the object you are expecting? – Tomer Apr 23 '13 at 18:47
  • This is what throws me off. I do see array of my objects as it should be. Edited to show debugger output. – katit Apr 23 '13 at 18:49

1 Answers1

2

So, the issue is that for...in loops you over the keys to properties of an object, rather than values of the object.

So if you have an object like

var x = {
    a: "A",
    b: "B"
}

for...in will spit out 'a' and 'b'. Since arrays are objects, for...in with an array will give you something very similar: A string for each index into the array. So, with var a= [1, 2, 3], for...in of a will result in '0', '1', '2', rather than 1, 2, 3.

Use a construct like below to do what you want, instead.

var sss = vm.tripData();
for (var i = 0; i < sss.length; i++) {
    var sh2 = sss[i];
    sh2.isVisible(false);
}
Colin DeClue
  • 2,194
  • 3
  • 26
  • 47
  • 1
    It's worth nothing that `for...in` iterates over the `keys` of the properties on an object, and not the `values`, which is why the current value of `sh2` is, in fact, `"0"`. – cwharris Apr 23 '13 at 19:19