Reputation: 1043
I've written a js lib that needs to work in ie8 and I've been asked not to use jQuery as part of the implementation. Part of the js lib requires searching an array for a matching value. Modern browsers support the array indexOf() function which will accomplish this. However, since my js lib needs to support ie8 I won't be able to use this function. Initially I wrote the following custom function:
function inArray(anArray, aValue)
{
for (var i = 0; i < anArray.length; i++)
if (anArray[i] === aValue) return true;
//value was not in array
return false;
}
However, this morning it occured to me that it would be better to write this using prototypal inheritance. What would be a good way to rewrite this using prototypal inheritance? Also, is there a way I can go into the direct source code used for the ES standard, copy the indexOf() function and paste it into my custom js lib? Not sure if this is possible or not but it seems like a good way to port snippets without reinventing the wheel.
Upvotes: 3
Views: 476
Reputation: 175098
As a general rule, having your own namespace and using a function like you've described is probably better for a library, something like this:
MyLib.inArray = function(array, value) {
// implementation here
};
You could modify the prototype of Array
with the ES6 function .includes()
like so:
Array.prototype.includes = Array.prototype.includes || function(needle) {
// implementation here
};
and then you can use it like so:
[1, 2, 3].includes(3); // true
(Note that if it already exists, we don't override it)
However, this is generally bad practice to do in a library, because you're modifying a reference to a build-in function that other scripts on the page may rely on! Additionally, properties added this way will show up when iterating the array with for..in
, which is extremely undesirable.
Upvotes: 1
Reputation: 1075755
You're probably best off with a utility function you pass the array into, such as the inArray
in your question.
You could add a shim for Array#indexOf
or includes
or similar to Array.prototype
, but if you did, it would become enumerable and show up in for-in
loops. People shouldn't use for-in
to loop through arrays, but sadly, they sometimes do. If they do in your codebase or any library your codebase includes, that will be a problem.
Unfortunately, you can't make it non-enumerable because IE8 doesn't support Object.defineProperty
(except on HTML elements, oddly).
Upvotes: 1