简体   繁体   English

如何取消设置数组中的条目?

[英]How to unset an entry in an array?

If I declare a new Array() and add a value, but then I want to remove that value, how do I do so? 如果我声明一个新的Array()并添加一个值,但是我想删除该值,我该怎么办? Setting the value = null simply creates a null value at that index, while removing that index with splice reduces the size of the array. 设置value = null只是在该索引处创建一个空值,而使用splice删除该索引会减小该数组的大小。 See below: 见下文:

class CustomArray {
  constructor(size) {
    this.arr = new Array(size)
  }

  describe() {
    console.log(this.arr.length)
    this.arr.forEach(num => console.log(num))
  }

  insert(idx, val) {
    this.arr.splice(idx, 1, val)
  }

  remove(idx) {
    this.arr[idx] = null
  }

  remove2(idx) {
    this.arr.splice(idx, 1)
  }

}

let myArr = new CustomArray(20)
myArr.insert(3, 100)
myArr.remove(3)
myArr.describe() //outputs 20 for length and `null`


let mySecondArr = new CustomArray(20)
mySecondArr.insert(3, 100)
mySecondArr.remove(3) //ouputs 19 for length

//how do I remove all values AND retain length?

You can use delete operator. 您可以使用delete操作符。 delete will create an empty slot at that particular index. delete将在该特定索引处创建一个空槽。 According to MDN MDN称

When you delete an array element, the array length is not affected . 删除数组元素时, 数组长度不受影响 This holds even if you delete the last element of the array. 即使您删除数组的最后一个元素,这也成立。

 class CustomArray { constructor(size) { this.arr = new Array(size) } describe() { console.log(this.arr.length) this.arr.forEach(num => console.log(num)) } insert(idx, val) { this.arr.splice(idx, 1, val) } remove(idx) { delete this.arr[idx] } remove2(idx) { this.arr.splice(idx, 1) } } let myArr = new CustomArray(20) myArr.insert(3, 100) myArr.remove(3) myArr.describe() 

I believe delete arr[i] is what you're looking for. 我相信delete arr[i]是你正在寻找的。 The length of the array doesn't change, the value is set to undefined, but it is also ignored by functions such as map and forEach , so they never run code for a deleted value. 数组的长度不会更改,该值设置为undefined,但mapforEach等函数也会忽略它,因此它们永远不会为已删除的值运行代码。

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

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