在IE8及以下中,不支持aplly方法中的第二个参数是 伪数组
需要对push方法进行封装。
将 push 的判断,放入一个沙箱中:
好处:在页面加载的时候就会执行这段代码,保证了代码只会检测一次
以后的操作中直接使用调用 push 即可。
jquery源码中也是这样封装的,在用jquery操作DOM元素时,不需要考虑此兼容性问题啦
var push = [].push;
try {
// 判断 push 是否可用
var container = document.createElement("div");
container.innerHTML = "<p></p><p></p>";
push.apply([], container.childNodes);
} catch(e) {
// 自己封装push方法
push = {
apply: function(target, els) {
var j = target.length;
i = 0;
while(target[j++] = els[i++]) {}
target.length = j - 1;
}
};
} finally {
container = null;
}
例如:
var arr = [1, 2, 3];
[].push(arr, {"a", "b"});
console.log(arr); // [1, 2, 3, "a", "b"] IE8也可正常输出