IE <= 8 .splice() not working

IE <= 8 .splice() not working

本文关键字:not working splice lt IE      更新时间:2023-09-26

我有一些简单的代码,你可以在我的小提琴。它可以在所有浏览器和IE9中正常发出警报,但不能在IE8和ie7中发出警报。

var func = function( x ) {
    var slice = [].slice,
        args = slice.call( arguments ),
        pass = args.splice(1);
    alert( pass );
};
func( 'a', 1, 2 );

编辑使用解决方案,我张贴了我在这里使用的:http://jsfiddle.net/7kXxX/4/

我在不知道有多少参数的情况下使用这个,这就是为什么我使用"arguments"

ECMAScript第三版标准要求第二个deleteCount参数:

Array.prototype.splice(start, deleteCount [, item1 [, item2[,...]]])

MSDN文档显示IE遵循此标准:

arrayObj.splice(start, deleteCount, [item1[, item2[, . . . [,itemN]]]])

Firefox的SpiderMonkey允许第二个参数是可选的(和其他现代浏览器一样):

array.splice(index , howMany[, element1[, ...[, elementN]]])
array.splice(index[, howMany[, element1[, ...[, elementN]]]])

描述:

多少一个整数,表示要删除的旧数组元素的数量。如果howMany为0,则不删除任何元素。在这种情况下,你应该指定至少一个新元素。如果没有howMany参数指定的(上面的第二个语法,这是一个SpiderMonkey扩展),索引之后的所有元素都被删除。

来源:

  • http://bclary.com/2004/11/07/a-15.4.4.12
  • http://msdn.microsoft.com/en-us/library/wctc5k7s%28v=VS.85%29.aspx
  • https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/splice

Splice有必需的第二个参数:

http://jsfiddle.net/7kXxX/2/

pass = args.splice(1,2);

第二个可选参数是新浏览器中的扩展,如果未定义则假定数组的其余部分

https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/splice

Slice会更合适如果你想要从1 -到末尾的元素,看起来没有任何理由从args中删除元素

我对IE中Array.prototype.splice的解决方案:

(function () {
    'use strict';
    var originalSplice = Array.prototype.splice;
    Array.prototype.splice = function (start, deleteCount) {
        // convert the weird, not-really-an-array arguments array to a real one
        var args = Array.prototype.slice.call(arguments);
        // IE requires deleteCount; set default value if it doesn't exist
        if (deleteCount === undefined) {
            args[1] = this.length - start;
        }
        // call the original function with the patched arguments
        return originalSplice.apply(this, args);
    };
}());
var func = function (x) 
{
    alert ([].slice.call (arguments, 1))
}
func( 'a', 1, 2 );

我不熟悉这个特殊的问题,但是你试过Sugar.js吗?它有一些方法可能为您工作(我相信用from替换splice会工作)。