How to fix Array indexOf() in JavaScript for Internet Explorer browsers

前端 未结 10 1460
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-11-22 03:09

If you have worked with JavaScript at any length you are aware that Internet Explorer does not implement the ECMAScript function for Array.prototype.indexOf() [includin

相关标签:
10条回答
  • 2020-11-22 03:53

    Alternatively, you could use the jQuery 1.2 inArray function, which should work across browsers:

    jQuery.inArray( value, array [, fromIndex ] )
    
    0 讨论(0)
  • 2020-11-22 03:54

    With the Underscore.js

    var arr=['a','a1','b'] _.filter(arr, function(a){ return a.indexOf('a') > -1; })

    0 讨论(0)
  • 2020-11-22 03:57

    This was my implementation. Essentially, add this before any other scripts on the page. i.e. in your master for a global solution for Internet Explorer 8. I also added in the trim function which seems to be used in allot of frameworks.

    <!--[if lte IE 8]>
    <script>
        if (!Array.prototype.indexOf) {
            Array.prototype.indexOf = function(obj, start) {
                for (var i = (start || 0), j = this.length; i < j; i++) {
                    if (this[i] === obj) {
                        return i;
                    }
                }
                return -1;
            };
        }
    
        if(typeof String.prototype.trim !== 'function') {
            String.prototype.trim = function() {
                return this.replace(/^\s+|\s+$/g, '');
            };
        };
    </script>
    <![endif]-->
    
    0 讨论(0)
  • 2020-11-22 04:03

    The full code then would be this:

    if (!Array.prototype.indexOf) {
        Array.prototype.indexOf = function(obj, start) {
             for (var i = (start || 0), j = this.length; i < j; i++) {
                 if (this[i] === obj) { return i; }
             }
             return -1;
        }
    }
    

    For a really thorough answer and code to this as well as other array functions check out Stack Overflow question Fixing JavaScript Array functions in Internet Explorer (indexOf, forEach, etc.).

    0 讨论(0)
提交回复
热议问题