【问题标题】:Javascript Array ProblemJavascript数组问题
【发布时间】:2010-01-21 11:00:11
【问题描述】:

为什么 JavaScript 返回错误的数组长度?

var myarray = ['0','1'];
delete myarray[0];
alert(myarray.length); //gives you 2

【问题讨论】:

    标签: javascript arrays


    【解决方案1】:

    “删除”不是修改数组,而是修改数组中的元素

     # x = [0,1];
     # delete x[0]
     # x
     [undefined, 1]
    

    你需要的是array.splice

    【讨论】:

      【解决方案2】:

      你必须使用 array.splice - 见http://www.w3schools.com/jsref/jsref_splice.asp

      myarray.splice(0, 1);
      

      这将删除第一个元素

      【讨论】:

      • 是的。另一个代码也删除了该项目。但它不会更新长度。
      【解决方案3】:

      根据this docs,删除操作符不会改变数组的长度。您可以为此使用 splice()。

      【讨论】:

        【解决方案4】:

        来自 Array 的 MDC 文档:

        "当你删除一个数组元素时, 数组长度不受影响。为了 例如,如果你删除 a[3],a[4] 是 仍然 a[4] 和 a[3] 是未定义的。这 即使您删除最后一个也保留 数组元素(删除 a[a.length-1])。”

        https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Operators/Special_Operators/delete_Operator

        https://developer.mozilla.org/En/Core_JavaScript_1.5_Reference/Objects/Array

        【讨论】:

          【解决方案5】:

          您可以使用John Resig 的不错的 remove() 方法来做到这一点:

          Array.prototype.remove = function(from, to) {
            var rest = this.slice((to || from) + 1 || this.length);
            this.length = from < 0 ? this.length + from : from;
            return this.push.apply(this, rest);
          };
          

          // Remove the second item from the array
          array.remove(1);
          // Remove the second-to-last item from the array
          array.remove(-2);
          // Remove the second and third items from the array
          array.remove(1,2);
          // Remove the last and second-to-last items from the array
          array.remove(-2,-1);
          

          【讨论】:

            【解决方案6】:

            这是正常行为。 delete() 函数不会删除索引,只会删除索引的内容。因此,数组中仍有 2 个元素,但在索引 0 处,您将拥有 undefined

            【讨论】:

              猜你喜欢
              • 2011-05-04
              • 1970-01-01
              • 1970-01-01
              • 2017-06-23
              • 2021-09-09
              • 2022-01-18
              • 2013-05-18
              • 2010-11-18
              • 1970-01-01
              相关资源
              最近更新 更多