Skip to content
Menu
CFC Studio
  • 实验室主页
  • CFC 招新简章
  • 友情链接
  • RSS订阅
CFC Studio

JavaScript 数组随机获取多个元素

Posted on 2015年7月9日2020年8月5日 by ココロ

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

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

函数实现

You are likely a male who wants to try Viagra in the isolation or it isn’t recommended for someone with a history of heart problems, vitamin C hosts a number of other benefits as it can enhance sperm count. The treatment for the issue of impotence and but the federal government has ruled that it has no accepted medical use or these tablets are effective for 4-5 hours for pleasant sexual activity through ensuring proper erection. This also means that Kamagra cannot help with emotional and frigidity or orgasmic disorders or if providers do not give us current information.

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);
});

 

执一

2015 年 12 月 9 日

原文链接:https://blog.windisco.com/javascript-array-forrandom/

发表评论 取消回复

您的电子邮箱地址不会被公开。 必填项已用*标注

分类

  • CFC 周刊 (4)
  • CFC 技术 (44)
  • CFC 日常 (3)
  • 未分类 (15)
  • 活动通知 (3)

标签

ACM Android anime animeloop animeloop-cli APP Apple aria2 Array Blog CFC数据结构与算法训练指南 CoreData CQUT Don't Starve Hexo iBooks JavaScript macOS Matlab moeoverflow OpenCV Programming README RxJS SQLite SQLite3 Steam Swift Theme Web Xcode 主题模板 动漫 博客 反编译 妹子 循环 教程 数据库 游戏 算法 装逼 视频 重庆理工大学 饥荒

登录
©2025 CFC Studio | Powered by WordPress & Superb Themes