【问题标题】:IE <= 8 .splice() not workingIE <= 8 .splice() 不工作
【发布时间】:2012-01-10 02:29:10
【问题描述】:

我有一些简单的代码,您可以在 my fiddle 中看到。它在所有浏览器和 IE9 中都能正常发出警报,但在 IE8 或 7 中则不行。

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/

我在不知道有多少参数出现的情况下使用它,这就是我使用“参数”的原因

【问题讨论】:

  • 您希望收到什么警报?

标签: javascript


【解决方案1】:

ECMAScript 3rd edition standard 需要第二个 deleteCount 参数:

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

MSDN docs 表明 IE 遵循这个标准:

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

Firefox 的 SpiderMonkey 允许 second argument to be optional(与其他现代浏览器一样):

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

说明:

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

来源:

【讨论】:

    【解决方案2】:

    Splice 有一个必需的第二个参数:

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

    pass = args.splice(1,2);
    

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

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

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

    【讨论】:

      【解决方案3】:

      我对 IE 中 Array.prototype.splice 的解决方案(read more here):

      (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);
          };
      }());
      

      【讨论】:

      • 无需将args 设为数组。只需使用arguments 对象。
      • 这是 IE 6-9 所需要的。根据我的 browserstack 研究,IE 6-9 无法写入 arguments 对象。
      【解决方案4】:
      var func = function (x) 
      {
          alert ([].slice.call (arguments, 1))
      }
      
      func( 'a', 1, 2 );
      

      【讨论】:

      • 你应该详细说明一下并解释你做了什么。只是代码没有删减它!
      • 另一方面,切片更适合所呈现的用例。
      【解决方案5】:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-09-13
        • 2013-02-14
        • 2013-02-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多