解决浏览器兼容问题

来源:互联网 发布:淘宝店铺宝贝卖点怎么写 编辑:程序博客网 时间:2024/06/04 00:43
浏览器兼容问题
  • indexOf 在ECMA-262 标准 的第5版中被加入,但并非所有的浏览器都支持该方法。(在低版本浏览器下出现对象不支持此属性或方法)
<!DOCTYPE html><html lang="en"><head>    <meta charset="UTF-8">    <title>Demo1</title></head><script>    var a = [2, 9, 9];    alert(a.indexOf(9));</script></html>

这里写图片描述

解决方案(其它函数同理)
<!DOCTYPE html><html lang="en"><head>    <meta charset="UTF-8">    <title>Demo2</title></head><body></body><script>    // Production steps of ECMA-262, Edition 5, 15.4.4.14    // Reference: http://es5.github.io/#x15.4.4.14    if (!Array.prototype.indexOf) {        Array.prototype.indexOf = function(searchElement, fromIndex) {            var k;            // 1. Let O be the result of calling ToObject passing            //    the this value as the argument.            if (this == null) {                throw new TypeError('"this" is null or not defined');            }            var O = Object(this);            // 2. Let lenValue be the result of calling the Get            //    internal method of O with the argument "length".            // 3. Let len be ToUint32(lenValue).            var len = O.length >>> 0;            // 4. If len is 0, return -1.            if (len === 0) {                return -1;            }            // 5. If argument fromIndex was passed let n be            //    ToInteger(fromIndex); else let n be 0.            var n = +fromIndex || 0;            if (Math.abs(n) === Infinity) {                n = 0;            }            // 6. If n >= len, return -1.            if (n >= len) {                return -1;            }            // 7. If n >= 0, then Let k be n.            // 8. Else, n<0, Let k be len - abs(n).            //    If k is less than 0, then let k be 0.            k = Math.max(n >= 0 ? n : len - Math.abs(n), 0);            // 9. Repeat, while k < len            while (k < len) {                // a. Let Pk be ToString(k).                //   This is implicit for LHS operands of the in operator                // b. Let kPresent be the result of calling the                //    HasProperty internal method of O with argument Pk.                //   This step can be combined with c                // c. If kPresent is true, then                //    i.  Let elementK be the result of calling the Get                //        internal method of O with the argument ToString(k).                //   ii.  Let same be the result of applying the                //        Strict Equality Comparison Algorithm to                //        searchElement and elementK.                //  iii.  If same is true, return k.                if (k in O && O[k] === searchElement) {                    return k;                }                k++;            }            return -1;};}</script><script>    var a = [2, 9, 9];    alert(a.indexOf(9));</script></html>
了解更多
  • 学习笔记