Pick random value from firebase snapshot

前端 未结 2 1273
自闭症患者
自闭症患者 2021-01-05 23:09

I\'m using firebase\'s foreach to get each child in a tree from this url

Objective, when the page loads grab a random item from firebase and show it

data str

2条回答
  •  天涯浪人
    2021-01-05 23:58

    It's not possible to grab a random item from the list in Firebase, unfortunately. You can do limit(1) to grab the first item, or endAt().limit(1) to grab the last item.

    If you're using forEach, you can also grab all the items like you are and then picking one at random, using Math.random. For example:

    var i = 0;
    var rand = Math.floor(Math.random() * snapshot.numChildren());
    snapshot.forEach(function(snapshot) {
      if (i == rand) {
        // picked random item, snapshot.val().
      }
      i++;
    });
    

提交回复
热议问题