jimy
jimy

Reputation: 4908

Unexpected output when iterating through an array with a for( ... in ...) loop

<html>
<head>
<script type="text/javascript">


Array.prototype.getUnique = function () {
    var o = new Object();
    var i, e;
    for (i = 0; e = this[i]; i++) {o[e] = 1};
    var a = new Array();
    for (e in o) {a.push (e)};
    return a;
}

function Perform(){
    var arr = new Array();

    arr[0] = "hello";
    arr[1] = "world";

    for(i in arr){
        console.log(arr[i]);
    }
}

</script>
</head>
<body onload="Perform()">
</body>
</html>

The result of above code in console is

hello
world
function()

From where does the last function() come from?

Upvotes: 0

Views: 473

Answers (2)

Stephen Chung
Stephen Chung

Reputation: 14605

for ... in in JavaScript DOES NOT ITERATE AN ARRAY. Forget your other programming languages -- this is JavaScript, the language with similar syntax that means completely different things.

for ... in iterates through all the properties of the object, including all propertes in its prototype chain.

Therefore, always use hasOwnProperty to check whether the property is defined on the object itself:

for (var name in obj) {
  if (obj.hasOwnProperty(name)) {
    doSomething(obj[name]);
  }
}

You should not use for ... in to iterate an array. Use an index instead.

Search SO for hundreds of similar questions on this topic.

Upvotes: 4

David Tang
David Tang

Reputation: 93694

The function() is coming from the prototype - it is the getUnique function.


To avoid this, you shouldn't be iterating through arrays with a for .. in loop. Use the plain old:

for (var i = 0; i < arr.length; i++)

In cases where you must use for .. in (for example, iterating through keys of an object), you should always check hasOwnProperty():

for (var i in arr) {
    if (arr.hasOwnProperty(i)) {
        console.log(arr[i]);
    }
}

Upvotes: 2

Related Questions