使用.each()两次

时间:2012-11-30 17:14:54

标签: javascript jquery

我使用这个脚本创建一个随机数序列,使用数组的值,并将这些数字应用到两个div列表中

var shuffle = function(v) {
    for (var j, x, i = v.length; i; j = parseInt(Math.random() * i), x = v[--i], v[i] = v[j], v[j] = x);
    return v;
};

var randorder = shuffle([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]);
var index = 0;

$('.Questions').each(function() {
    $(this).addClass('question' + (randorder[index++]));
});

$('.answers').each(function() {
    $(this).addClass('answer' + (randorder[index++]));
});

问题是脚本返回到类回答结果“answerundefined。”

记住两个集合必须具有相同的顺序,以匹配问题和答案。

由于

4 个答案:

答案 0 :(得分:3)

很难说,因为我不知道你有多少.Questions.answers,但当你看到undefined时,就意味着你超出了界限randorder数组。所以,你至少需要在循环之间将索引设置为零:

var index = 0;

$('.Questions').each(function() {
    $(this).addClass('question' + (randorder[index++]));
});
index = 0;
$('.answers').each(function() {
    $(this).addClass('answer' + (randorder[index++]));
});

您需要将索引设置回0的原因是因为当您完成循环.Questions时,索引的值为20.因此,当您循环遍历.answers时,索引已经从20到39.你想要0-19,所以你需要重置它。

此外,您可能想要检查您是否仍在界限内:

var randcount = randorder.length;
$('.Questions').each(function() {
    if (randcount > index) {
        $(this).addClass('question' + (randorder[index++]));
    }
});

答案 1 :(得分:1)

将整个事情转变为randorder(一次)将更容易且自然地容错。

var randorder = shuffle([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]);
var $questions = $('.Questions');
var $answers = $('.answers');

$.each(randorder, function(i, r) {
    $questions.eq(i).addClass('question' + r);
    $answers.eq(i).addClass('answer' + r);
});

当然,你仍然需要确保原始的[1, ... 20]数组是正确的长度来调整所有问题,所以最好自动生成数组以响应问题/答案集合的长度。

您可以使用shuffle()的修改版本执行此操作,其中在进行混洗之前生成整数序列(毫无疑问存在更好的算法)。

var shuffle = function(n) {
    var v = [];
    for(var i=0; i<n; i++) {
        v.push(i);
    }
    for (var j, x, i = v.length; i; j = parseInt(Math.random() * i), x = v[--i], v[i] = v[j], v[j] = x);
    return v;
};

var $questions = $('.Questions'),
    $answers = $('.answers'),
    randorder = shuffle(Math.min($questions.length, $answers.length));//in case questions and answers are different lengths we choose the lower length.

$.each(randorder, function(i, r) {
    $questions.eq(i).addClass('question' + r);
    $answers.eq(i).addClass('answer' + r);
});

注意:shuffle()返回一个从0到n的整数混洗数组,而不是1到n,这可能是原始问题的原因。

答案 2 :(得分:0)

索引是针对问题的,在增加之后,您可能只会因为回答$ .each而获得未定义。检查索引值。

由于

答案 3 :(得分:0)

var index = 0;

// Runs 20 times, index starts at = 0
$('.Questions').each(function() {
    $(this).addClass('question' + (randorder[index++]));
});

// Run 20 times, index starts at 20
// index = 0 << You need this.
$('.answers').each(function() {
    // randorder[index++] << index = 20, doesn't exist in your array, hence undefined
    $(this).addClass('answer' + (randorder[index++]));
});

我试图展示的是你使用相同的索引,但从不将它重置为0,所以你经常从0到20的迭代计数。正确的解决方案是添加索引= 0在第二个.each(..);

之前