zoukankan      html  css  js  c++  java
  • push方法的兼容性问题

    在IE8及以下中,不支持aplly方法中的第二个参数是 伪数组

    需要对push方法进行封装。

    将 push 的判断,放入一个沙箱中:
    好处:在页面加载的时候就会执行这段代码,保证了代码只会检测一次
    以后的操作中直接使用调用 push 即可。
    jquery源码中也是这样封装的,在用jquery操作DOM元素时,不需要考虑此兼容性问题啦
     1 var push = [].push;
     2 try {
     3     // 判断 push 是否可用
     4     var container = document.createElement("div");
     5     container.innerHTML = "<p></p><p></p>";
     6     push.apply([], container.childNodes);
     7 } catch(e) {
     8     // 自己封装push方法
     9     push = {
    10         apply: function(target, els) {
    11             var j = target.length;
    12                 i = 0;
    13             while(target[j++] = els[i++]) {}
    14             target.length = j - 1;
    15         }
    16     };
    17 } finally {
    18     container = null;
    19 }

     例如:

    var arr = [1, 2, 3];

    [].push(arr, {"a", "b"});

    console.log(arr);  // [1, 2, 3, "a", "b"]  IE8也可正常输出

  • 相关阅读:
    .NET实现Excel文件的读写 未测试
    权限管理设计
    struts1中配置应用
    POJ 2139 Six Degrees of Cowvin Bacon(floyd)
    POJ 1751 Highways
    POJ 1698 Alice's Chance
    POJ 1018 Communication System
    POJ 1050 To the Max
    POJ 1002 4873279
    POJ 3084 Panic Room
  • 原文地址:https://www.cnblogs.com/2010master/p/6051968.html
Copyright © 2011-2022 走看看