今天写代码,才发现 IE 下的array 的splice方法的bug
var a=["a","b"];
a.splice(0);
alert(a.length) // 在IE 下是2, 在谷歌下是 0
按照定义,splice()的第二个参数不写,就是删除到末尾,不知道为啥,IE就认为一个都不删除。
经查证,问题出在IE8及以下版本,可以修复此bug, 网上给的方案是
// check if it is IE and it's version is 8 or older if (document.documentMode && document.documentMode < 9) { // save original function of splice var originalSplice = Array.prototype.splice; // provide a new implementation Array.prototype.splice = function() { var arr = [], i = 0, max = arguments.length; for (; i < max; i++){ arr.push(arguments[i]); } // if this function had only one argument // compute 'deleteCount' and push it into arr if (arr.length==1) { arr.push(this.length - arr[0]); } // invoke original splice() with our new arguments array return originalSplice.apply(this, arr); }; }