The objects created by the built-in constructor functions such as Array
, String
, and even Object
and Function
can be augmented (or enhanced) through the use of prototypes. This means that you can, for example, add new methods to the Array
prototype, and in this way you can make them available to all arrays. Let's see how to do this.
In PHP, there is a function called in_array()
, which tells you if a value exists in an array. In JavaScript, there is no inArray()
method (although in ES5 there's indexOf()
, which you can use for the same purpose). 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 have access to the new method. Let's test this.
> var colors = ['red', 'green', 'blue']; > colors.inArray('red'); true > colors.inArray('yellow'); false
That was nice and...