ในการแทนที่รายการแบบสุ่ม ให้ใช้ random() พร้อมกับ map()
ตัวอย่าง
ต่อไปนี้เป็นรหัส -
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()); ในการรันโปรแกรมข้างต้น คุณต้องใช้คำสั่งต่อไปนี้ -
node fileName.js.
ที่นี่ ชื่อไฟล์ของฉันคือ demo278.js
ผลลัพธ์
สิ่งนี้จะสร้างผลลัพธ์ต่อไปนี้บนคอนโซล -
PS C:\Users\Amit\javascript-code> node demo278.js John David Bob Adam Carol Adam