1

我正在做一个关于删除数组内对象的测试......因为这是一个测试,所以这是一个非正式的代码..

<script type="text/javascript">

// initialize array and objects
var fruits = new Array();

var z = {
  test1: "test0",
  test2: "test2"
}

fruits.push(z);
var z2 = {
  test1: "test1",
  test2: "test2"
}
fruits.push(z2);
var z3 = {
  test1: "test2",
  test2: "test2"
}
fruits.push(z3);
var z4 = {
  test1: "test3",
  test2: "test2"
}
fruits.push(z4);
var z5 = {
  test1: "test4",
  test2: "test2"
}
fruits.push(z5);

// display array length
document.write("array length is " + fruits.length + "<br>");

// traverse array
for(var x = 0; x < fruits.length; x++){

  // display object content in array
  document.write(fruits[x].test1 + " ");

  // delete object in array where variable test1 is equal to "test2"
  if(fruits[x].test1 == "test2"){
    fruits.splice(x, 1);
    //document.write("array length is " + fruits.length + "<br>");
  }
}
</script>

现在这段代码工作正常(删除数组上的一个对象),但它删除了我要删除的那个之后的那个(在上面的代码中,我想删除索引 2 中的对象,但它删除了索引 3 中的对象)

我在这段代码中做错了什么?

蒂亚:)

4

3 回答 3

6

您永远不应该在迭代数组时尝试更改它。相反,将要删除的元素的索引保存在变量中,并在 for 循环之后将其删除。

于 2011-09-02T08:56:21.457 回答
0

使用underscore.js中实现的“过滤器” :

_.filter(fruits, function (fruit) {
    return fruit.test1 !== "test2";
});

这具有在可用的情况下使用快速、本机 JavaScript 方法(“过滤器”)的优势。

于 2011-09-02T09:13:03.383 回答
0

这应该有效:

<script type="text/javascript">

    // initialize array and objects
    var fruits = new Array();

    var z = {
      test1: "test0",
      test2: "test2"
    }

    fruits.push(z);
    var z2 = {
      test1: "test1",
      test2: "test2"
    }
    fruits.push(z2);
    var z3 = {
      test1: "test2",
      test2: "test2"
    }
    fruits.push(z3);
    var z4 = {
      test1: "test3",
      test2: "test2"
    }
    fruits.push(z4);
    var z5 = {
      test1: "test4",
      test2: "test2"
    }
    fruits.push(z5);

    // display array length
    document.write("array length is " + fruits.length + "<br>");

    // traverse array
    for(var x = 0; x < fruits.length; x++){

      // display object content in array
      document.write(fruits[x].test1 + " ");

      // delete object in array where variable test1 is equal to "test2"
      if(fruits[x].test1 == "test2"){
        fruits.splice(x-1, 1);
        //document.write("array length is " + fruits.length + "<br>");
      }
    }
    </script>
于 2011-09-02T08:49:10.670 回答