angularfire2数组操作 [英] angularfire2 array manipulation

查看:50
本文介绍了angularfire2数组操作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Firebase中处理数组的正确方法是什么?我试图在单击按钮时在数组或数字内切换值.因此每个数字仅存在一次,例如单击按钮12,然后将12添加到firebase中的数组,如果再次单击则将其删除.

Whats the correct way to deal with arrays in firebase? I'm trying to toggle a value within an array or numbers when clicking a button. so each number exist only once, say button 12, is clicked, then 12 is added to the array in firebase, if clicked again then it's removed.

这是我的代码,但是,它不会拼接,每次都会重新添加数字.

this is my code, however, it does not splice, the number is added again every time.

blockTime(time: number) {
const idx = _.indexOf(this.times, time);
if (idx >= 0) {
     this.times.splice(idx, 1);
   } else {

  this.times.push(time);
   }
}

推荐答案

当您尝试切换数组中的值时,请重新考虑数据结构.每当您执行 array.contains(...) array.indexOf(...)时,您可能应该使用类似集合的数据结构.

When you're trying to toggle a value in an array, reconsider your data structure. Whenever you do array.contains(...) or array.indexOf(...) you probably should be using a set-like data structure.

由于JavaScript/JSON没有实数集,因此您通常(至少在Firebase上)通过使用具有 true 值和您的集项作为键的对象来模拟它们.然后突然您的操作变得更加整洁:

Since JavaScript/JSON doesn't have real sets, you typically emulate them (on Firebase at least) by using an object with true values and your set-items as keys. Then suddenly you operation becomes a lot cleaner:

blockTime(time: number) {
  if (!this.times[time]) {
    this.times[time] = true;
  }
  else {
    delete this.times[time];
  }
}

或者,如果您可以将非阻塞时隙保留为 false 值,则可以:

Or if you're fine with keeping non-blocked time slots with a false value:

blockTime(time: number) {
  this.times[time] = !(this.times[time] || false);
}

请注意,在Firebase中存储此类数据时,最好确保您的密钥是字符串,以避免Firebase SDK的数组强制.您只需在键前面加上字符串即可,例如

Note that when storing this type of data in Firebase, it is best to make sure your keys are strings to avoid the array coercion of the Firebase SDKs. You can simply do this by prefixing the keys with a string, e.g.

blockTime(time: number) {
  var key = "time"+number;
  if (!this.times[key]) {
    this.times[key] = true;
  }
  else {
    delete this.times[key];
  }
}

这篇关于angularfire2数组操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆