JS - Lodash工具库的使用详解18(生成随机数)

作者: hgweb 发布时间: 2019-10-16 浏览: 5470 次 编辑

十八、生成随机数

1,random 函数介绍

random 函数原型如下,它将产生一个包括 lower upper 之间的随机数:

  • 如果只提供一个参数,则返回一个 0 到提供数之间的数。
  • 如果 floating 设为 true,或者 lower upper 是浮点数,则结果返回浮点数。
_.random([lower=0], [upper=1], [floating])

2,生成随机整数

(1)下面代码将生成 0~5 之间的随机整数:

console.log(_.random(0, 5));
console.log(_.random(0, 5));
console.log(_.random(0, 5));
console.log(_.random(0, 5));

原文:JS - Lodash工具库的使用详解18(生成随机数)


(2)上面代码也可以简化成如下形式:

_.random(5);

3,生成随机浮点数

(1)如果 lower upper 参数是浮点数,则结果返回浮点数。

console.log(_.random(0, 2.2));
console.log(_.random(0, 2.2));
console.log(_.random(0, 2.2));
console.log(_.random(0, 2.2));<a href="https://www.hangge.com/blog/cache/detail_2582.html">
</a>

原文:JS - Lodash工具库的使用详解18(生成随机数)


(2)如果 floating 参数设为 true,则结果返回浮点数。

_.random(5, true); //生成0~5之间的浮点数 

JS Lodash工具库的使用详解系列:

JS - Lodash工具库的使用详解1(使用debounce函数实现防抖)

JS - Lodash工具库的使用详解2(使用throttle函数实现节流)

JS - Lodash工具库的使用详解3(String字符串操作函数)

JS - Lodash工具库的使用详解4(Array数组函数1:查找指定元素、或索引)

JS - Lodash工具库的使用详解5(Array数组函数2:获取部分数组片段)

JS - Lodash工具库的使用详解6(Array数组函数3:移除、修改原数组内容)

JS - Lodash工具库的使用详解7(Array数组函数4:数组排序、打乱)

JS - Lodash工具库的使用详解8(Array数组函数5:数组与对象间的转换)

JS - Lodash工具库的使用详解9(Array数组函数6:如果不是数组强制转成数组)

JS - Lodash工具库的使用详解10(Array数组函数7:根据指定规则进行分组、统计)

JS - Lodash工具库的使用详解11(Array数组函数8:创建指定范围数字的数组)

JS - Lodash工具库的使用详解12(创建一个只能调用1次、n次的函数)

JS - Lodash工具库的使用详解13(创建一个对某函数结果取反的函数)

JS - Lodash工具库的使用详解14(浅拷贝,深拷贝)

JS - Lodash工具库的使用详解15(深比较,判断是否包含某属性或属性值)

JS - Lodash工具库的使用详解16(判断是否为空)

JS - Lodash工具库的使用详解17(类型检查)

JS - Lodash工具库的使用详解18(生成随机数)


原文出自:www.hangge.com 转载请保留原文链接:https://www.hangge.com/blog/cache/detail_2582.html