0
<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?

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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]);
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.