0

我有 2 个 div,#col1并且#col2,我需要在其中生成一些带有水果名称的 div。

到目前为止,我有:

var fruitArray = ['apples','banana','orange','grapes'];
for (fruit in fruitArray) {
    $('<div class="'+fruitArray[fruit]+'"></div>').appendTo('#col1').doSomething(); 

    $('<div id="'+fruitArray[fruit]+'"></div>').appendTo('#col2').doSomething(); 
}

结果是这样的:

<div id="#col1">
    <div class="apples"></div>
    <div class="banana"></div>
    <div class="orange"></div>
    <div class="grapes"></div>
</div>
<div id="#col2">
    <div id="apples"></div>
    <div id="banana"></div>
    <div id="orange"></div>
    <div id="grapes"></div>
</div>

如何随机化数组,使其看起来像:

<div id="#col1">
    <div class="orange"></div>
    <div class="apples"></div>
    <div class="orange"></div>
    <div class="grapes"></div>
</div>
<div id="#col2">
    <div id="grapes"></div>
    <div id="orange"></div>
    <div id="apples"></div>
    <div id="banana"></div>
</div>
4

1 回答 1

0

简单shuffle扩展:

Array.prototype.shuffle = function() {
    var shuffledArray = [];
    while (this.length) {
        shuffledArray.push(this.splice(Math.random() * this.length, 1)[0]);
    }
    while (shuffledArray.length) {
        this.push(shuffledArray.pop());
    }
    return this;
}

像这样使用它

var fruitArray = ['apples','banana','orange','grapes'].shuffle();
for (var i = 0; i < fruitArray.length; i++) {            
    $('<div class="'+fruitArray[i]+'"></div>').appendTo('#col1').doSomething(); 

    $('<div id="'+fruitArray[i]+'"></div>').appendTo('#col2').doSomething(); 
}
于 2012-05-22T10:59:05.477 回答