JavaScript 如何创建一个包含随机值的数组
任务是使用JavaScript生成一个包含随机值的数组。下面讨论了两种方法:
方法1
- 使用 Math.random() 和 Math.floor() 方法获取随机值。
- 逐个将值添加到数组中(但这种方法可能会生成重复的值)。
示例: 下面示例实现了上述方法。
function gfg_Run() {
console.log(Array.from({
length: 10
}, () => Math.floor(Math.random() * 10)));
}
gfg_Run()
输出
[
8, 6, 4, 3, 9,
2, 8, 9, 7, 8
]
方法2
- 创建一个数组,并按顺序将值放入其中(例如,在循环中将1放在索引0处,2放在索引1处,3放在索引2处)。
- 将一个变量(tp)赋值为数组的长度。
- 在变量(tp)上运行一个循环。
- 在循环中使用 Math.random() 和 Math.floor() 方法获取数组的随机索引。
- 将这个数组值与索引(tp)交换,并将变量(tp)减1。
- 循环直到变量(tp)变为0。
示例: 这个示例实现了上述方法。
let a = []
for ( i = 0; i < 10; ++i) a[i] = i;
// Array like[1, 2, 3, 4, ...]
function createRandom(arr) {
let tmp, cur, tp = arr.length;
if (tp)
// Run until tp becomes 0.
while (--tp) {
// Generating the random index.
cur = Math.floor(Math.random() * (tp + 1));
// Getting the index(cur) value in variable(tmp).
tmp = arr[cur];
// Moving the index(tp) value to index(cur).
arr[cur] = arr[tp];
// Moving back the tmp value to
// index(tp), Swapping is done.
arr[tp] = tmp;
}
return arr;
}
function gfg_Run() {
console.log(createRandom(a));
}
gfg_Run()
输出
[
0, 9, 4, 3, 6,
8, 2, 7, 1, 5
]
极客教程