0

I declared the following function in JavaScript so I can see what is contained within an array.

Array.prototype.contains = function (obj) {
    var i = this.length;
    while (i--) {
        if (this[i] === obj) {
            return true;
        }
    }
    return false;
}

Added the above function... now when I do the following, the function is added to the array keys... This can be seen by comparing the output with the console.log lines below.

var obsr = {0: 'hi',1: 'go',3:'sss'};

var keys = Object.keys(obsr);

for (var i in keys){
    console.log(i);
    console.log(keys[i]);
    console.log("----");
}

The output is:

Object {0="hi", 1="go", 3="sss"}
["0", "1", "3"]
0
0
----
1
1
----
2
3
----
contains
function()
----

This is breaking code that uses the Object.keys() function since it's retrieving the function. What am I missing?

user3168961
  • 375
  • 1
  • 10
  • It's not `Object.keys`. It's `for...in`. Use [`hasOwnProperty`](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwnProperty) OR `for (var i = 0; i < keys.length; i++) {` to iterate over array. – Tushar Mar 21 '17 at 11:42
  • 1
    Instead of `contains`, you should just use the standard [`includes` method](http://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes) – Bergi Mar 21 '17 at 11:50
  • @Bergi yes. Beat me to it! Also, that is why closing immediately sometimes is a bad thing. Since he might have gotten some other useful information. – Aluan Haddad Mar 21 '17 at 11:51

0 Answers0