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

    2.22 sample

    2.22.1 语法:

    _.sample(list, [n])

    2.22.2 说明:

    从list中产生一个随机样本。传参n后返回n个随机元素,各元素不重复。

    2.22.3 代码示例:

    示例一:从list中随机产生一个样本

    var sample;
    
    //数组
    sample = _.sample([1, 2, 3, 4, 5]);
    console.log(sample); //may be => Number 3
    
    //对象
    sample = _.sample({a:1, b:2, c:3, d:4, e: 5}); 
    console.log(sample); //may be => Number 2
    
    //字符串
    sample = _.sample('12345'); 
    console.log(sample); //may be => String 5
    
    //arguments
    (function(){
    sample = _.sample(arguments); 
    console.log(sample); //may be => Number 1
    }(1, 2, 3, 4, 5));
    

    示例二:传递参数n

    var sample;
    
    //数组
    sample = _.sample([1, 2, 3, 4, 5], 3);
    console.log(sample); //may be => [4, 2, 3]
    
    //对象
    sample = _.sample({a:1, b:2, c:3, d:4, e: 5}, 3); 
    console.log(sample); //may be => [1, 2, 4]
    
    //字符串
    sample = _.sample('12345', 3); 
    console.log(sample); //may be => ["5", "1", "4"]
    
    //arguments
    (function(){
    sample = _.sample(arguments, 3); 
    console.log(sample);  //may be => [3, 2, 4]
    }(1, 2, 3, 4, 5));
    

    传递n后,返回的是数组。

    2.22.3 传递参数n的变化

    var list = [1, 2, 3, 4, 5];
    var sample;
    
    sample = _.sample(list, -1);
    console.log(sample); //=> []
    
    sample = _.sample(list, 0);
    console.log(sample); //=> []
    
    //传1返回的也是数组
    sample = _.sample(list, 1);
    console.log(sample); //may be => [1]
    
    sample = _.sample(list, 3);
    console.log(sample); //may be => [1, 2, 4]
    
    sample = _.sample(list, 5);
    console.log(sample); //may be => [5, 3, 1, 2, 4]
    
    sample = _.sample(list, 10);
    console.log(sample); //may be => [2, 4, 5, 1, 3]
    
    • 传递了参数n返回的都是数组
    • n <= 0 返回空数组
    • n > 0 && n < list.length 返回的数组长度为n
    • n >= list.length返回的数组长度为list.length

    2.22.4 产生的一个样本内,各元素不会重复

    var list = [1, 2, 3, 4, 5];
    var sample;
    
    _(3).times(function(){
        sample = _.sample(list, 5);
        console.log(sample);
    });
    

    2.22.5 非集合情况都返回undefined

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

    2.22.6 简单的random,元素的值可能重复

    var list = ['a', 'b', 'c', 'd'];
    var sample = [];
    
    for(var i = 0; i < list.length; i++) {
        var n = Math.floor(Math.random() * list.length);
        sample.push(list[n]);
    }
    console.log(sample); //maybe => ["c", "d", "c", "a"]
    
  • 相关阅读:
    Windows平台使用Gitblit搭建Git服务器图文教程
    yapi部署文档
    Yapi学习笔记
    利用微软认知服务实现语音识别功能
    对.Net Core结合Docker和Jexus的实践
    python-集合、字典
    python-文件操作
    python-函数
    python-运算、分支、深浅拷贝
    linux下的文件结构
  • 原文地址:https://www.cnblogs.com/kyo4311/p/5178324.html
Copyright © 2011-2022 走看看