Reputation: 51
In my javascript code I often need to check if an expression in some enumerable list like this:
if ((a == 'value1') || (a == 'value2') || (a == 'value3')) { ... do smth ... }
I can write something like this:
if (['value1', 'value2', 'value3', 'value4'].indexOf ( a ) ) { ... do smth ... }
but I think it's unreadable.
I add property in_arr for Object.prototype:
Object.defineProperty(Object.prototype, 'in_arr', {
value : function(arr) {
for (var i=0; i<arr.length; i++) {
if ( arr[i] == this.valueOf() ) {
return true;
}
}
return false;
},
enumerable: false
})
And now I can write like this:
if (a.in_arr([ 'value1', 'value2', 'value3', 'value4' ]) { ... do smth ... }
I think, it's looks good. But I want to ask: Is it safe to change Object.prototype like this? And what about perfomance?
Upvotes: 0
Views: 90
Reputation: 1906
It's not recomended to extend Object.prototype, this will lead to strange behaviours and there is no need to do it one way if there is a less dangerous one like a simple function.
in_array(obj, [ 'a', 'b', 'c' ]);
You can even create a utils object
utils.in_array(obj, [ 'a', 'b', 'c' ]);
Once I've said that...
This looks very similar to Extending Object.prototype JavaScript and I totally agree with Alex Wayne:
I think it's fine if it works in your target environment.
Also I think prototype extension paranoia is overblown. As long as you use hasOwnProperty() like a good developer that it's all fine. Worst case, you overload that property elsewhere and lose the method. But that's your own fault if you do that.
Upvotes: 0
Reputation: 525
Wrong way to change system objects like Array, Object etc. Because conflicts may occur if anyone do such changes
Upvotes: 0
Reputation: 106365
Create an enumeration hash, like this:
var enumHash = {
value1: true,
value2: true,
value3: true
// actually it doesn't matter which value to assign:
// even undefined will do, as you check the existence of a property, not its value
};
... then just check the existence of a property:
if (someValue in enumHash) { ... }
That'll be both faster than Array.indexOf
and more readable.
Upvotes: 3
Reputation: 1798
you can just use Array.prototype.indexOf(el)
[ 'value1', 'value2', 'value3', 'value4' ].indexOf(a.valueOf()) !== -1
Upvotes: -2