/* * Function: removeItem * This function removes all occurrences of this item * * Parameter: * item - The item being removed. Can be primitive or object. If object must be same instance. */ Array.prototype.removeItem = function(item){ var length = this.length, i; for(i=0; i < length; i++){ var member = this.pop(); if(member !== item){ this.unshift(member); } } };Now items can be removed from any array just by calling that method.
//Remove Numbers var numberArr = [1,2,3,2]; console.log(numberArr); // 1 2 3 2 numberArr.removeItem(2); console.log(numberArr); // 1 3 //Remove string var numberArr = ["1","2","3","2"]; console.log(numberArr); // "1" "2" "3" "2" numberArr.removeItem("2"); console.log(numberArr); // "1" "3"
How cool is that? Even objects defined with native code can be extended to increase their utility and ease of use.
No comments:
Post a Comment