JavaScript 数组随机获取多个元素

JavaScript Dec 9, 2015

今天撸代码实现了 array.forEach(); 的类似方法 array.forRandom();

这个方法可以随机不重复地获取数组中多个元素并进行相应处理。

函数实现

Array.prototype.forRandom = function(n, callback) {
    // 如果 n 大于数组长度,则直接调用 forEach();
    if (n >= this.length) {
        this.forEach(function(element) { callback(element); });
        return;
    }
    // 深复制
    var temp = [];
    this.forEach(function(element, index) { temp[index] = element; });

    var len = temp.length;
    // 随机不重复
    for (var i = 0; i < n; i++) {
        var index = parseInt(Math.random() * 100) % len;
        callback(temp[index]);
        temp[index] = temp[--len];
    }
}

用法

var testArray = [1, 2, 3, 4, 5, 6, 7, 8];

// 从数组中随机取 3 个元素进行操作
testArray.forRandom(3, function(element) {
    console.log(element);
});

Tags

Great! You've successfully subscribed.
Great! Next, complete checkout for full access.
Welcome back! You've successfully signed in.
Success! Your account is fully activated, you now have access to all content.