The built-in objects such as the constructor functions Array
, String
, and even Object,
and Function
can be augmented through their prototypes, which means that you can, for example, add new methods to the Array
prototype and in this way make them available to all arrays. Let's do this.
In PHP there is a function called in_array()
that tells you if a value exists in an array. In JavaScript there is no inArray()
method, so let's implement it and add it to Array.prototype
.
Array.prototype.inArray = function(needle) { for (var i = 0, len = this.length; i < len; i++) { if (this[i] === needle) { return true; } } return false; }
Now all arrays will have the new method. Let's test:
>>> var a = ['red', 'green', 'blue']; >>> a.inArray('red');
true
>>> a.inArray('yellow');
false
That was nice and easy! Let's do it again. Imagine your application often needs to reverse strings and you feel there should be a built...