Reputation: 1923
I have extended Array
prototype:
if(typeof Array.prototype.filter === 'undefined') Array.prototype.filter = function(fun /*, thisp*/){
var len = this.length;
if(typeof fun != "function") throw new TypeError();
var res = [], thisp = arguments[1];
for(var i=0;i<len;i++){
if(i in this){
var val = this[i]; // in case fun mutates this
if(fun.call(thisp, val, i, this)) res.push(val);
}
}
return res;
};
For example I have created array:
var A = [ 1, 2, 3, 4, 5 ];
Then I added extra properties to it, that I will use:
A.creator = 'Rustam';
A.created = new Date();
If I will use for-in
loop, and browser has not built-in support for Array.filter
, it will go through A.filter
.
I know this way:
for(var p in A) {
if (!A.hasOwnProperty(p)) continue
console.log(p)
};
Is there a way to make A.filter
hidden in for-in
without using hasOwnProperty
?
UPDATE to answer. Browser support:
Upvotes: 2
Views: 189
Reputation: 7624
To define a property which does not show up in loops, use Object.defineProperty
:
Object.defineProperty(Array.prototype, 'filter', {value:'XYZ'});
This extends Array.prototype
with a property called filter
with default property descriptors, including enumerable: false
, which causes the property to not show up in for( .. in ..)
loops.
PS: Will not work on older browsers I don't have the browser compatibility matrix for this API.
Upvotes: 4