When working with JavaScript, I often find myself needing to check if a particular value is included in an array. Typically, I would write something like:
if ((a == 'value1') || (a == 'value2') || (a == 'value3')) { ... do something ... }
However, I believe this approach can be difficult to read. To improve readability, I decided to add a custom method called in_arr to the 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
})
Now, I can simply use this new method in my code like so:
if (a.in_arr(['value1', 'value2', 'value3', 'value4'])) { ... do something ... }
I find this implementation to be more readable and organized. However, I have concerns about whether it is safe to modify the Object.prototype in this way. Additionally, I am curious about the potential impact on performance.