gpt4 book ai didi

javascript - 三元语句中的随机数

转载 作者:行者123 更新时间:2023-11-30 12:57:10 24 4
gpt4 key购买 nike

我借用了这个脚本(有 3 页)并添加了另外 2 页。问题是它只在列表中的前 3 个之间随机化。我也不太理解三元 if/else。如果 n 大于 3,则为 0。否则,如果 n 大于 8,则为 1。否则为 2?我做对了吗?这似乎是一种奇怪的方式。我如何让它在 1 和 5 之间随机化?

<script type="text/javascript">
(function(n){
var pages = ['Happy.html', 'Sad.html', 'Pensive.html', 'Eager.html', 'Inquisitive.html'];
n = n < 3? 0 : n < 8? 1 : 2;
window.location.replace(pages[n]);
})(Math.floor(Math.random() * 10));
</script>

最佳答案

你不需要三元运算符..你可以这样做

function(n){
//everything except the ternary operator
}(Math.floor(Math.random()*10)%5)

此表达式的输出随机在 0 和 4 之间,而不是 1 和 5。这是必需的,因为 5 个元素的数组的索引在 0 和 4 之间(含 0 和 4)。

关于javascript - 三元语句中的随机数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18639314/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com