Java Reference
In-Depth Information
return this[this.length -1];
}
Again, we can check that these work with a couple of examples:
var jla = ["Superman", "Batman", "Wonder Woman", "Flash",
"Aquaman"];
jla.first();
<< "Superman"
jla.last();
<< "Aquaman"
Another handy method that arrays lack is the delete() method. There is the delete
operator that we met in Chapter 3 , but the way this works is not very intuitive as it leaves a
value of null in place of the item that's removed. In that chapter, we saw that it is possible
to remove an item completely from an array using the splice() method. We can use this
to create a new method called delete() that removes an item from the array at the index
provided:
Array.prototype.delete = function(i) {
return self.splice(i,1);
}
A useful example of monkey-patching is to add support for methods that are part of the
specification, but not supported natively in some browsers. An example is the trim()
method, which is a method of the String prototype object, so all strings should inherit it.
It removes all whitespace from the beginning and the end of strings, but unfortunately this
method is not implemented in Internet Explorer version 8 or below. This can be rectified
using this polyfill code:
String.prototype.trim = String.prototype.trim ||
function() {
return this.replace(/^\s+|\s+$/,'');
}
Search WWH ::




Custom Search