在 JavaScript 数组中替换随机项?
在 JavaScript 中用数组中的其他项替换随机项。让我们来看一个例子;数组是:
Var array=[m,n,o,p]
让我们选择两个随机项替换为 a,而其他项保持其原始位置。如果 m 和 n 是随机选择的项,并且在一个实例中移除一个,则数组将是:
Changed array=[a,a,o,p]
让我们深入了解这篇文章,学习更多关于在 JavaScript 数组中替换随机项的内容。要替换随机项,请使用random()和map()。
使用 random() 方法
JavaScript 方法random()用于返回一个伪随机数或随机数,该数落在指定的范围内。必须通过占位符对象 Math 调用random()函数,因为它是的 Math 对象的静态函数。
语法
以下是random()的语法:
Math.random();
使用 map()
map()方法在对每个元素执行给定函数后,从调用数组的内容构建一个新数组。
语法
以下是map()的语法:
array.map(function(currentValue, index, arr), thisValue)
为了更好地理解在 JavaScript 中替换随机项,让我们来看以下示例。
示例
在下面的示例中,我们运行脚本以替换 JavaScript 数组中的随机项。
<!DOCTYPE html>
<html>
<body>
<script>
function randomone(array, count) {
return function() {
const indices = new Set();
do {
indices.add(Math.floor(Math.random() * array.length));
} while (indices.size < count)
return array.map((v, i) => indices.has(i) ? 1 : v);
};
}
var myArray = ['A', 'B', 'C', 'D'],
newarray = randomone(myArray, 2);
document.write(...newarray());
</script>
</body>
</html>
当脚本执行时,它将生成一个输出,其中包含一个值为“1”的数组,该值随机地替换在数组项之间。每当用户执行脚本时,这都会发生更改。
示例
考虑以下示例,这里我们运行脚本以获取唯一的随机索引,并循环遍历这些索引并将它们设置为 2。
<!DOCTYPE html>
<html>
<body>
<script>
var my_arr = ["ab", "bc", "cd", "de"];
const random = (num, count) => {
const set = new Set();
while (set.size < count) {
set.add(Math.floor(Math.random() * num));
}
return [...set];
};
const alter = (arr, count = 2) => {
const output = [...arr];
random(arr.length, count).forEach((index) => (output[index] = 2));
return output;
};
document.write(JSON.stringify(alter(my_arr)));
</script>
</body>
</html>
运行上述脚本后,将弹出输出窗口,显示生成的数组,其中值“2”由触发脚本的事件随机替换到数组中。
示例
执行以下脚本以观察如何在 JavaScript 数组中替换随机项。
<!DOCTYPE html>
<html>
<body>
<script>
function substituteRandomValue(names, size) {
return function() {
const index = new Set();
do {
index.add(Math.floor(Math.random() * names.length));
} while (index.size < size)
return names.map((value, counter) => index.has(counter) ? 'Adam' : value);
};
}
var names = ['John', 'David', 'Bob', 'Mike', 'Carol', 'Sam'],
result = substituteRandomValue(names, 2);
document.write(...result() + " < br > ");
</script>
</body>
</html>
当脚本执行时,事件被触发并显示一个数组,其中索引中有一个随机替换的值,并且每当用户执行脚本时,它都会不断变化。
广告
数据结构
网络
关系型数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP