如何清空或清除 javascript 中的对象数组 | Firestore-Vuejs

How to empty or clear an array of objects in javascript | Firestore - Vuejs

我想知道是否有清除或清空对象数组的方法,比方说我有这个对象数组,我从 firebase firestore 借来的,我用快照来做到这一点,这里是代码:

let siteButtonsData = firebase.firestore()
        .collection('app_settings')
        .doc('dashboard')
        .collection('main_panel')
        .onSnapshot(doc => {
          doc.forEach(doc => {
            this.arrObj.push(doc.data())
          });
        })

然后我的对象数组被正确填充,显示如下:

data() {
    return { 
      arrObj: [
       {
         action: 'one',
         id: 1,
         text: 'hello1'
       },
       {
         action: 'two',
         id: 2,
         text: 'hello2'
       },
       {
        action: 'three',
        id: 3,
        text: 'hello3'
       },
      ]
    }
}

我用 v-for 迭代 this.buttons 以在我的应用程序中创建一些动态内容,但是当我的 firestore 数据库发生某些变化并且快照更新它时,我得到了重复项,我希望清除从 firestore 更新之前的对象数组,所以我不会有重复项,但它不起作用,到目前为止我已经尝试过:

this.arrObj = [{}]
this.arrObj = [] //This option leaves me with no way to push the array of objects
this.arrObj.length = 0

无论我使用哪种方法,我都无法正确更新对象数组,第一次它很好地完成了从 firestore 收集数据的工作,但是一旦我更新了数据库,我就得到了重复项。

提前感谢您的帮助或提示

如果您想清空整个数组并转储所有元素怎么办?

您可以使用多种技术来创建空数组或新数组。

最简单和最快的技术是将数组变量设置为空数组:

var ar = [1, 2, 3, 4, 5, 6];//do stuffar = [];//一个新的空数组!

当您引用变量时,这可能会产生问题。对该变量的引用不会改变,它们仍将保留原始数组的值。这当然会造成错误。

这是此场景的过度简化示例:

var arr1 = [1, 2, 3, 4, 5, 6];var arr2 = arr1; // 通过另一个变量引用 arr1 arr1 = [];console.log(arr2); // 输出 [1, 2, 3, 4, 5, 6]

清除数组的一个简单技巧是将其长度 属性 设置为 0。

var ar = [1, 2, 3, 4, 5, 6];console.log(ar); // 输出 [1, 2, 3, 4, 5, 6]ar.length = 0;console.log(ar); // 输出 []

另一种不自然的技术是使用拼接方法,将数组长度作为第二个参数传递。这将 return 原始元素的副本,这可能对您的方案很方便。

var ar = [1, 2, 3, 4, 5, 6];console.log(ar); // 输出 [1, 2, 3, 4, 5, 6]ar.splice(0, ar.length);console.log(ar); // 输出 []

最后两个技巧不是创建新数组,而是改变数组的元素。这意味着参考文献也应该更新。

还有另一种方法,使用 while 循环。我觉得有点奇怪,但同时看起来很漂亮,所以可能会打动一些朋友!

var ar = [1, 2, 3, 4, 5, 6];console.log(ar); // 输出 [1, 2, 3, 4, 5, 6] while (ar.length) { ar.pop(); }console.log(ar); // 输出 []

这不是我清除 JavaScript 数组的方法,但它有效且可读。一些性能测试也表明这是最快的技术,所以它可能比我原先想象的要好!

在使用数组时,您始终需要确保 Vue 的反应系统正在捕获更改并更新视图。 Vue 会自动观察一些数组变异方法以确保更新,它们是 push()、pop()、shift()、unshift()、splice()、sort() 和 reverse()。 参见 https://vuejs.org/v2/guide/list.html#Mutation-Methods

至于你的例子,那么应该起作用的是:

let siteButtonsData = firebase.firestore()
        .collection('app_settings')
        .doc('dashboard')
        .collection('main_panel')
        .onSnapshot(doc => {
          this.arrObj.splice(0, this.arrObj.length);
          // I would think this works as well:
          // this.arrObj = [];
          doc.forEach(doc => {
            this.arrObj.push(doc.data())
          });
        })