JavaScript 在数组中替换随机的项吗

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>

当脚本被执行时,该事件被触发,显示一个带有随机替换值的索引数组,而且每当用户执行脚本时,它将不断改变。

Camera课程

Python教程

Java教程

Web教程

数据库教程

图形图像教程

办公软件教程

Linux教程

计算机教程

大数据教程

开发工具教程