JavaScript---不重复的随机数

来源:百度文库 编辑:神马文学网 时间:2024/04/27 17:05:42
代码:
程序代码
// @param list: an Array
// @param alias: name for getter function,
//               by default it's "getItem"

function RandomList(list, alias) {

    if (!list) { return; }

    var length = list.length;
    this.indexes = [];

    this.remainingItems = function(){
        return this.indexes.length;
    };

    this[alias || 'getItem'] = function(){
        var rand = Math.floor(Math.random() * this.indexes.length),
            item = list[this.indexes[rand]];
        this.indexes.splice(rand, 1);
        return item;
    };

    while (length--) {
        this.indexes[this.indexes.length] = length;
    }

}


用法:
程序代码
// List of fruit:
var fruits = [
    'Apple',
    'Banana',
    'Orange',
    'Melon',
    'Grape',
    'Pear'
];

var button = document.getElementById('the_button'),
    // Custom alias ('getFruit'):
basket = new RandomList(fruits, 'getFruit');

button.onclick = function() {
    if (!basket.remainingItems()) {
        alert('None left!');
    } else {
        alert( basket.getFruit() ); // < We're using the new alias!
        alert( 'Only ' + basket.remainingItems() + ' left in the basket!');
    }
}