获取四个唯一项并将它们添加到数组中

时间:2011-11-03 09:46:22

标签: javascript arrays loops

我100%确定此代码以前一直在使用。现在奇怪的是没有。

目标是为闪卡创建一个多项选择测验。我创建了一个数组来存储卡的ID:第一个是当前卡ID,然后是其他三个随机卡。我的目标是确保他们不会重复第一张卡或他们自己。

我就是这样做的:

    // Array of cards’ ids to use
    var randomCardsIds = [];

    // Get the active card’s element id, add it to the array
    randomCardsIds[0] = this.activeCardId;

    // Get the current cards collection
    var allCurrentCards = this.carouselEl.items.items;

    // Get three random ids of other cards
    var i = 0
    while (i<3) {

        // Get a random card element
        var randomCardEl = allCurrentCards[Math.floor(Math.random() * allCurrentCards.length)];
        // Get its id
        var randomCardElId = randomCardEl.body.down('.card').id;
        randomCardElId = randomCardElId.substring(randomCardElId.indexOf('_')+1);

        console.log(randomCardElId, randomCardsIds, randomCardsIds.indexOf(randomCardElId));

        // Make sure it is not in the array yet, and then add it
        if (randomCardsIds.indexOf(randomCardElId) == -1) {
            randomCardsIds.push(randomCardElId);
            i++;
        }
        // Otherwise, the loop will have to run again

    }

基本上,在一个循环中,对于每个项目,我检查它是否已经存在于数组中。如果没有,请将其推送到阵列,否则再次运行循环。这是控制台记录结果:

enter image description here

嗯,第一件事:它总是显示数组的最终状态:好像它已经填满了结果,这很奇怪。但最重要的是:脚本不能识别重复(例如,在第一个结果中,74重复,在倒数第二个,47)。

当它在第二个位置找到匹配时(显然返回1),它只返回不同于-1的东西。当匹配位于数组中的不同位置时,它总是返回-1。

我在这里做错了什么?

2 个答案:

答案 0 :(得分:0)

你在IE6中测试这个吗?问题是indexOf不适用于IE6。

如需替代方案,您可以查看Best way to find if an item is in a JavaScript array?

答案 1 :(得分:0)

shuffling algoruthm的变体似乎是最好的选择。