Based on all the answers which were mainly correct and taking into account the best practices suggested (especially not using Array.prototype directly), I came up with the below code. Let me know if there is anything you find wierd. But should be fine:
// Extending the core Array Object
MyArray.prototype = new Array();
MyArray.prototype.constructor= MyArray;
/**
* New array class constructor
*/
function MyArray() {
// Constructor code here
}
/**
* Excludes a value from array and returns the rest of array
* @param {string/number/boolean} excludedValue Value which should be removed
* @return {array}
*/
MyArray.prototype.without = function(excludedValue) {
var valueType = typeof excludedValue;
if (this.length < 1)
return [];
if (valueType == 'object' || valueType == 'array' || valueType == 'undefined')
throw "Argument can not be object, array or undefined";
for (var index in this) {
if (this[index] === excludedValue) {
this.splice(index, 1);
index--;
}
};
return this;
};
// How to use
var arr = new MyArray();
arr = [1,2,3,4,5,"name", false];
arr.without(1); // will change the array to [2,3,4,5,"name", false]
arr.without("name"); // will change the array to [2,3,4,5, false]
arr.without(false); // will change the array to [2,3,4,5]
arr.without([1,2]); // will throw error as argument can not be array
arr.without({bar: "foo"}); // will throw error as argument can not be object
indexOf
in IE. – Scotty.NET Sep 13 '13 at 7:48