在 JavaScript 中生成随机布尔值
本文介绍了如何使用 lodash 的 Math.random()
、数组和 _.sample(collection)
函数在 JavaScript 中生成随机布尔值。Math.random()
函数返回 0 到 1 之间的数字,其中 0 包括在内,而 1 则不包括在内。
_.sample(collection)
方法接受一个集合并从提供的集合中随机返回一个值。
要使用 lodash 的 _.sample(collection)
方法,请在 <head>
元素中添加以下代码行。
<script src="https://cdn.jsdelivr.net/npm/lodash@4.17.10/lodash.min.js"></script>
在 JavaScript 中使用 Math.random()
来生成随机布尔值
Math.random()
返回 [0,1)
范围内的任何数字,其中 0 包含在内,但 1 不包含在内。
我们可以将此范围分成两个分区。第一个分区范围从 [0,0.5)
,第二个从 [0.5,1)
。
我们为什么要这样做呢?因为我们给 true
和 false
的发生机会相等。如果小于 0.5,则为真
;否则,布尔值将为 false
。
例子:
var random_boolean_value = Math.random() < 0.5;
console.log(random_boolean_value)
输出:
false
让我们编写一个更详细的代码,看看它是否在小于 0.5 时返回 true
。
请参阅以下代码段。
for (var i = 0; i < 10; i++) {
var rand_number = Math.random();
console.log(rand_number);
var random_boolean_value = rand_number < 0.5;
console.log(random_boolean_value);
}
输出:
0.06464303463834886
true
0.27911502950509837
true
0.9811371177556913
false
0.539086724802587
false
0.3440647317306955
true
0.8779878853066467
false
0.2889025142115962
true
0.6346333079296975
false
0.28944321051370525
true
0.35970422088985354
true
在 JavaScript 中使用数组生成随机布尔值
让我们学习一个更优化的版本,以在 JavaScript 中生成随机布尔值。
检查以下实例,我们使用 Math.random()
产生一个随机值,乘以 Array.prototype.length
。然后,使用 Math.floor()
方法四舍五入最接近的整数。
例子:
const sample = arr => arr[Math.floor(Math.random() * arr.length)];
console.log(sample([true, false]));
输出:
true
在 JavaScript 中使用 _.sample(collection)
方法生成随机布尔值
例子:
<html>
<head>
<script src="https://cdn.jsdelivr.net/npm/lodash@4.17.10/lodash.min.js"></script>
</head>
<body>
<script>
console.log(_.sample([true, false]));
</script>
</body>
</html>
输出:
false
相关文章
Do you understand JavaScript closures?
发布时间:2025/02/21 浏览次数:108 分类:JavaScript
-
The function of a closure can be inferred from its name, suggesting that it is related to the concept of scope. A closure itself is a core concept in JavaScript, and being a core concept, it is naturally also a difficult one.
Do you know about the hidden traps in variables in JavaScript?
发布时间:2025/02/21 浏览次数:178 分类:JavaScript
-
Whether you're just starting to learn JavaScript or have been using it for a long time, I believe you'll encounter some traps related to JavaScript variable scope. The goal is to identify these traps before you fall into them, in order to av
How much do you know about the Prototype Chain?
发布时间:2025/02/21 浏览次数:150 分类:JavaScript
-
The prototype chain can be considered one of the core features of JavaScript, and certainly one of its more challenging aspects. If you've learned other object-oriented programming languages, you may find it somewhat confusing when you start
用 jQuery 检查复选框是否被选中
发布时间:2024/03/24 浏览次数:102 分类:JavaScript
-
在本教程中学习 jQuery 检查复选框是否被选中的所有很酷的方法。我们展示了使用直接 DOM 操作、提取 JavaScript 属性的 jQuery 方法以及使用 jQuery 选择器的不同方法。你还将找到许多有用的
jQuery 中的 Window.onload 与 $(document).ready
发布时间:2024/03/24 浏览次数:180 分类:JavaScript
-
本教程演示了如何在 jQuery 中使用 Window.onload 和 $(document).ready 事件。