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

Javascript 获取四个唯一项并将它们添加到数组中,javascript,arrays,loops,Javascript,Arrays,Loops,我百分之百确定这段代码以前一直有效。现在奇怪的是,它没有 目标是为抽认卡创建一个选择题测验。我创建了一个数组来存储卡的id:第一个是当前卡的id,然后是其他三个随机的id。我的目标是确保他们不会重复第一张牌或自己 我就是这样做的: // Array of cards’ ids to use var randomCardsIds = []; // Get the active card’s element id, add it to the array rando

我百分之百确定这段代码以前一直有效。现在奇怪的是,它没有

目标是为抽认卡创建一个选择题测验。我创建了一个数组来存储卡的id:第一个是当前卡的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

    }
//要使用的卡ID数组
var randomCardsIds=[];
//获取活动卡的元素id,将其添加到阵列中
randomCardsIds[0]=this.activeCardId;
//获取当前卡片集合
var allCurrentCards=this.carouselEl.items.items;
//随机获得三张其他卡的ID
变量i=0

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


您可以检查A上的变体是否是这里的最佳选择。

不,我正在Chrome和Safari中尝试此功能。您是否为(int I=0;I)尝试过类似的简单循环