【问题标题】:How to reset array indexes in JavaScript array如何在 JavaScript 数组中重置数组索引
【发布时间】:2017-02-17 17:36:15
【问题描述】:

我正在使用 React 和 Firebase 网络数据库。

在下面的代码中,dbRef 指向一个 Firebase 数据库树,其中包含一个 array 字符串。此数组的某些元素已被删除,导致索引为空。

[
  "0": "first",
  "1": "next",
  "6": "skipped indexes 2 - 5"
]

我目前正在做:

dbRef.set([...currentList, newItem])

但是,我想确保传递给set 的数组没有任何null 索引。在 JS 中执行此操作的最佳方法是什么? (如果重要,我正在使用 babel)

【问题讨论】:

  • 您不应该将数组存储在 Firebase 中,因为您尝试解决此问题的确切原因。见:firebase.googleblog.com/2014/04/…
  • @MathewBerg,感谢您指出这一点。我将改用对象。

标签: javascript reactjs web firebase firebase-realtime-database


【解决方案1】:

您可以过滤掉它不再有的条目:

// In ES2015+
theArray = theArray.filter((_, index) => theArray.hasOwnProperty(index));

// In ES5 and earlier
theArray = theArray.filter(function(_, index) { return theArray.hasOwnProperty(index); });

例子:

var theArray = ['a', 'b', 'c', 'd'];
delete theArray[2];
console.log("before", JSON.stringify(theArray));
theArray = theArray.filter((_, index) => theArray.hasOwnProperty(index));
console.log("after", JSON.stringify(theArray));

【讨论】:

  • 感谢您的回答。使用hasOwnProperty(index) 是否比使用.filter(val => val) 更好/更安全?
  • 是的,我现在明白了。如果valfalsey,那么它将被filter 删除。
【解决方案2】:

简单的方法

testArray.filter(function(val){return val});

【讨论】:

  • 这也将删除存在但包含 ""0NaNnullundefinedfalse 的条目。
猜你喜欢
  • 1970-01-01
  • 2012-07-09
  • 1970-01-01
  • 2011-11-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-06-28
相关资源
最近更新 更多