Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> JavaScript

Thay thế ngẫu nhiên các phần tử trong mảng JavaScript

Để thay thế ngẫu nhiên các phần tử, hãy sử dụng random() kết hợp map().

Ví dụ

Mã minh họa:

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); 
console.log(...result());

Để chạy chương trình, sử dụng lệnh:

node tenFile.js

Tên file ở đây là demo278.js.

Kết quả

Đầu ra trên console (ví dụ):

PS C:\Users\Amit\javascript-code> node demo278.js
John David Bob Adam Carol Adam