【问题标题】:Meteor: Shuffle array then map indexesMeteor:随机排列数组然后映射索引
【发布时间】:2014-12-30 13:53:33
【问题描述】:

我正在尝试在将索引映射到它之前从 mongo 集合(items)中打乱一组对象。

我现在拥有的方式不包括改组,仅将索引映射到模板助手中的每个对象。像这样:

dayItems: function() {
    return this.dayItems.map(function(item, index) {
        item.index = index;
        return item;
    });
},

我尝试过在没有映射索引的情况下对项目进行改组(可行)。像这样:
编辑:对不起,这似乎并不能单独工作。任何想法为什么?

dayItems: function() {
    return _.shuffle(this.dayItems);
},

我想在添加索引之前使用 underscore.js 随机播放函数对项目进行随机播放 不知何故,这两个函数似乎彼此不喜欢,因为当我组合它们时它不会返回任何东西。

这是我尝试过的:

return _.shuffle(this.dayItems).map(function(item, index) {
    item.index = index;
    return item;
});

谢谢


编辑 2:这是一些附加代码。使用以下代码在路由器中获取项目:

dayItems: Items.find({
    gender: "male",
    dayOrNight: "day",
    isOutfit: true,
    isPrecipitation: true,
    tempId: "f",
    published: true,
}, {sort: {submitted: -1}, limit:6}),

有趣的是,当我在分配索引之后 洗牌时,它会按预期工作:

return _.shuffle(this.dayItems.map(function(item, index) {
    item.index = index;
    return item;
}));

【问题讨论】:

    标签: javascript arrays sorting meteor


    【解决方案1】:

    好的,a.dorosty 的回答是正确的。问题来自 this.dayItems,它返回了一个 mongo 光标,而不是一个数组。

    这行得通:

    return _.chain(this.dayItems.fetch()).shuffle().map(function(item, index) {
        item.index = index;
        return item;
    }).value();
    

    【讨论】:

      【解决方案2】:

      试试这个

      return _.chain(this.dayItems).shuffle().map(function(item, index) {
          item.index = index;
          return item;
      }).value();
      

      【讨论】:

      • 谢谢,但它不起作用。我认为问题来自于shuffle函数:我尝试单独使用它并没有返回预期的数组,只是一堆空对象
      猜你喜欢
      • 1970-01-01
      • 2018-03-24
      • 2012-02-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多