不一致的Javascript行为(IF语句嵌套在while循环中)

Jac*_*erd 1 javascript random jquery while-loop

我正在尝试编写一个简单的Javascript(jQuery)函数,该函数随机显示6个Div.可能的11个.代码排序,它会随机显示大约一半的Div,但它在4到8之间变化.

谁能告诉我哪里出错了?它似乎应该如此简单但我完全迷失了!

我的代码:

<div class="offer">Offer 1</div>
<div class="offer">Offer 2</div>
... snip
<div class="offer">Offer 11</div>

<script src="query.min.js" type="text/javascript"></script>


 <script>
            var changed = 0;

            while (changed < 6) {


                $('.offer').each(function(index) {

                    if (changed < 6) {

                        var showOrNot = Math.floor(Math.random() * 2);

                        if (showOrNot == 1) {

                            $(this).addClass('offershow');
                            changed += 1;
                            $(this).text(changed); //debugging looking for the current value of changed 
                        }


                    }


                })


            }

        </script>
Run Code Online (Sandbox Code Playgroud)

Luk*_*ger 6

现在的问题是你有一堆无关的尝试.如果你有一个有11个球的球并有50%的机会移除每个球,你可能会在0到11之间得到任意数量的球.概率向中心倾斜,但是你没有得到六个而且正好六个每一次.

你想要的是删除六个,正好六个球,任意选择.

尝试更像这样的东西:

var offers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11];
for (var i = 0; i < 6; i += 1) {
    // choose a remaining offer at random
    var index = Math.floor(Math.random() * offers.length);

    // retrieve the item being shown
    var item = $('.offer').eq(offers[index]);
    item.addClass('offerShow');

    // remove this offer from the list of possibilities
    offers.splice(index, 1);
}
Run Code Online (Sandbox Code Playgroud)

编辑:在评论中,OP澄清了他真正想要的是采取一个任意大小的报价列表,并显示其中六个.下面提供的代码解决了这个问题,而不是原始问题中的严格要求.我将离开原始代码以供参考.

var OFFERS_TO_SHOW = 6;  // config, of sorts

// make sure no offers are shown now
$('.offer').removeClass('offerShow');

// show offers selected at random
for (var i = 0; i < OFFERS_TO_SHOW; i += 1) {
    // get a list of offers not already being shown
    var candidates = $('.offer').not('.offerShow');

    // select one from this list at random
    var index = Math.floor(Math.random() * offers.length);

    // show this offer by adding the offerShow class
    candidates.eq(index).addClass('.offerShow');
}
Run Code Online (Sandbox Code Playgroud)