Best Way to Find if an Item Is in a JavaScript Array
Finding an object within an array is a common task in JavaScript programming. The ideal approach depends on browser compatibility and performance considerations.
Modern Solution: Includes()
For modern browsers compatible with ECMAScript 2016, use the includes() method. It simplifies the search:
arr.includes(obj);
Fallback for Older Browsers: IndexOf
For browsers without includes(), use indexOf with a comparison to -1:
function include(arr, obj) { return (arr.indexOf(obj) != -1); }
Custom Implementations for Compatibility
For browsers like IE6-8 that don't support indexOf, define your own implementation:
// Mozilla's version if (!Array.prototype.indexOf) { Array.prototype.indexOf = function(searchElement /*, fromIndex */) { // Implementation omitted for brevity }; } // Daniel James's version if (!Array.prototype.indexOf) { Array.prototype.indexOf = function (obj, fromIndex) { // Implementation omitted for brevity }; }
The above is the detailed content of How Can I Efficiently Check if an Item Exists in a JavaScript Array?. For more information, please follow other related articles on the PHP Chinese website!