2

Sorry this is a very small segment of code:

var arr = [2,4,6,8];
var obj = {};
for (var i in arr) {
    obj[arr[i]] = arr[i] * 2;
}

What I expect it to do is output the values of arr in an object, and return those values doubled. My does that but also includes this:

'function () {\r\n  var result = [];\r\n  for (var property in this)\r\n    result.push(property);\r\n  return result;\r\n}': NaN

Can anyone explain to me why this happens? Thank you.

Xelad1
  • 175
  • 1
  • 18
  • 2
    You're using the wrong kind of loop for an Array. Use a `for` statement instead. What's going on is that either `Array.prototype` or `Object.prototype` has been extended with a method. Because `for-in` enumerates all enumerable properties, even when inherited, you're including the method in the loop. – cookie monster May 19 '14 at 05:51
  • 2
    ...it looks like a loose version of `Object.keys`, so it's probably on `Object.prototype`. – cookie monster May 19 '14 at 05:53
  • You totally messed up the OOP approach, `i` is property of `arr` but you are using it as index.. Either use a full for loop `for(var i = 0; i < arr.length; i++)` or use `obj[i] = i * 2` – brainless coder May 19 '14 at 05:54
  • …which makes this related to [How to define method in javascript on Array.prototype and Object.prototype so that it doesn't appear in for in loop](http://stackoverflow.com/q/13296340/1048572) – Bergi May 19 '14 at 05:55
  • 2
    @Mahmud: I think that's what he intends. He wants the result to be `{"2":4, "4":8, "8":16, "16":32}` – cookie monster May 19 '14 at 05:55
  • @cookiemonster Oh I see... then he can try using `eval` if its conflicting with some prototype – brainless coder May 19 '14 at 05:56

0 Answers0