在 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>

當指令碼執行時,事件被觸發並顯示一個數組,其中索引中有一個隨機替換的值,並且每當使用者執行指令碼時,它都會不斷變化。

更新於:2023年4月21日

289 次檢視

啟動你的職業生涯

完成課程獲得認證

開始學習
廣告