HTML and CSS Reference
In-Depth Information
> a.pop()
1
> a.push(6)
5
These methods are derived from the prototype object for arrays called Array.prototype
(which in turn has Object.prototype as its prototype).
Due to the fact that all arrays are based on the same prototype, if we add methods to this
prototype, they immediately become available to all arrays. Remember, prototypes are just
objects themselves; therefore they can be modified just like any other object.
For instance, arrays do not have a “contains” method. It might be useful to implement a
method that accepts a single parameter, and then returns true if the array contains that value.
This can be written as follows:
> Array.prototype.contains = function (val) {
for (var i = 0; i < this.length; i++) {
if (this[i] === val) {
return true;
}
}
return false;
}
We can now execute the following:
> [1,2,3,4,5].contains(3)
true
> a.contains(6)
Search WWH ::




Custom Search