简体   繁体   English

在JavaScript中使用删除运算符

[英]using delete operator in javascript

After deleting an object property using delete objec.prop3[1] , null is getting replaced in that object property's place. 使用delete objec.prop3 [1]删除对象属性后,该对象属性的位置将替换为null。

for ex: 例如:

objec: {
  prop1: "aa",
  prop2: "bb",
  prop3: [{
    item1: "i1",
    item2: "i2"
  }, {
    item1: "i3",
    item2: "i4"
  }]
}
for deleting {
  item1: "i3",
  item2: "i4"
}

i am using 我在用

for (i = 0; i < objec.prop3.length; i++) {
  if (objec.prop3[i].item2 == "i4") {
    delete object.prop3[i]
  }
}
obtained output:
  objec: {
    prop1: "aa",
    prop2: "bb",
    prop3: [{
        item1: "i1",
        item2: "i2"
      },
      null
    ]
  }
required output:
  objec: {
    prop1: "aa",
    prop2: "bb",
    prop3: [{
      item1: "i1",
      item2: "i2"
    }]
  }

You are trying to delete an element from a array and not a key value pair, to do that you can not use delete instead use some method to delete an element from array.. 您正在尝试从数组而不是键值对中删除一个元素,这样做不能使用delete而是使用某种方法从数组中删除一个元素。

for (i = 0; i < objec.prop3.length; i++) {
  if (objec.prop3[i].item2 == "i4") {
    object.prop3.splice(i, 1);
  }
}

The splice() method adds/removes items to/from an array, and returns the removed item(s). splice()方法在数组中添加/删除项目,并返回删除的项目。

Note: This method changes the original array. 注意:此方法更改原始数组。

array.splice(index,howmany,item1,.....,itemX) array.splice(index,howmany,item1,.....,itemX)

index: Required. 索引:必填。 An integer that specifies at what position to add/remove items, Use negative values to specify the position from the end of the array 一个整数,指定要在什么位置添加/删除项目,请使用负值指定从数组末尾开始的位置

howmany: Required. 数量:必填。 The number of items to be removed. 要删除的项目数。 If set to 0, no items will be removed 如果设置为0,则不会删除任何项目

item1, ..., itemX: Optional. item1,...,itemX:可选。 The new item(s) to be added to the array 要添加到数组中的新项目

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM