我有一个包含 50 个对象的数组作为元素。
每个对象包含一个由 4 个元素组成的数组:
var all = [{
question: "question 1 goes here",
options: ["A", "B", "C", "D"]
}, ... {
question: "question 50",
options: ["A", "B", "C", "D"]
}]
我想随机选择 10 个元素并保存到另外两个数组中,这是我想要随机播放选项的数组之一。但是在洗牌时,两个数组都会受到影响。
var selected = [];
var shuffled = [];
for(let i = 0; i < 10; i++) {
let rand = Math.floor(Math.random() * all.length);
selected.push(all[rand]);
shuffled.push(all[rand]);
all.splice(rand, 1);
for(let j = 3; j > 0; j--) {
let rand2 = Math.floor(Math.random() * j);
[
shuffled[i].options[j],
shuffled[i].options[rand2]
] = [
shuffled[i].options[rand2],
shuffled[i].options[j]
];
}
}
console.log(selected); // is shuffled too
console.log(shuffled);
我该如何防止呢?
我觉得我错过了一些非常简单的东西,但我无法发现它。