IE does not support Array includes or String includes methods

后端 未结 7 1228
温柔的废话
温柔的废话 2020-11-29 06:04

I have been working on a project and developing a JavaScript framework. The original code is about 700 lines so I only pasted this line. The includes method doesn\'t work on

相关标签:
7条回答
  • 2020-11-29 06:26

    This is a polyfill for TypeScript projects, taken from https://developer.mozilla.org/nl/docs/Web/JavaScript/Reference/Global_Objects/Array/includes and modified to be valid TypeScript:

    if (!Array.prototype.includes) {
        Object.defineProperty(Array.prototype, 'includes', {
            value: function(searchElement, fromIndex) {
    
                if (this == null) {
                    throw new TypeError('"this" is null or not defined');
                }
    
                const o = Object(this);
                // tslint:disable-next-line:no-bitwise
                const len = o.length >>> 0;
    
                if (len === 0) {
                    return false;
                }
                // tslint:disable-next-line:no-bitwise
                const n = fromIndex | 0;
                let k = Math.max(n >= 0 ? n : len - Math.abs(n), 0);
    
                while (k < len) {
                    if (o[k] === searchElement) {
                        return true;
                    }
                    k++;
                }
                return false;
            }
        });
    }
    
    0 讨论(0)
提交回复
热议问题