zoukankan      html  css  js  c++  java
  • underscorejs-shuffle学习

    2.21 shuffle

    2.21.1 语法

    _.shuffle(list)

    2.21.2 说明

    返回一个随机乱序的list副本数组, 使用 Fisher-Yates shuffle 来进行随机乱序.

    2.21.3 代码示例

    示例一:将集合洗牌,返回数组

    
    //数组
    var arr = [1, 2, 3, 4, 5, 6];
    console.log(_.shuffle(arr)); //may be => [2, 4, 5, 1, 6, 3]
    
    //字符串
    console.log(_.shuffle('123456')); //may be => ["5", "1", "2", "6", "4", "3"]
    
    //对象返回的也是数组。
    var obj = {a:1, b:2, c:3, d:4, e:5};
    console.log(_.shuffle(obj)); //may be => [1, 3, 4, 2, 5]
    
    //arguments
    (function(){
        console.log(_.shuffle(arguments)); //may be => [1, 3, 4, 5, 2]
    }(1, 2, 3, 4, 5))
    
    

    示例二:返回的是新组数。

    var arr1 = [1, 2, 3, 4, 5, 6];
    var arr2 = _.shuffle(arr1);
    
    console.log(arr1); // [1, 2, 3, 4, 5, 6]
    console.log(arr2); //may be => [2, 4, 6, 1, 5, 3]
    

    2.21.4 处理其他非集合,返回空数组

    console.log(_.shuffle([])); //=> []
    console.log(_.shuffle(1)); //=> []
    console.log(_.shuffle(null)); //=> []
    console.log(_.shuffle(undefined)); //=> []
    console.log(_.shuffle(NaN)); //=> []
    

    2.21.5 用_.sample来实现同样的功能

    function shuffle(list){
        return _.sample(list, list.length);
    }
    
    var list = [1, 2, 3, 4, 5, 6];
    var arr1 = _.shuffle(list);
    var arr2 = shuffle(list);
    
    console.log(arr1); //may be => [1, 4, 5, 2, 6, 3]
    console.log(arr2); //may be => [6, 5, 1, 2, 3, 4]
    
    
  • 相关阅读:
    nginx 自启动脚本
    debian开机启动管理
    vagrant up connection time out
    vagrant在windows下的使用
    Office Web Apps Server
    邻接表模型中的节点移动
    Managing Hierarchical Data in MySQL(邻接表模型)[转载]
    play mp3 in c#
    2014年5月份第3周51Aspx源码发布详情
    2014年5月份第2周51Aspx源码发布详情
  • 原文地址:https://www.cnblogs.com/kyo4311/p/5178322.html
Copyright © 2011-2022 走看看