删除已随机选取的项目



我想删除从名称选择器中随机选择的项目。所以一个项目不会出现两次。

const Names = [
{
name: 'Name1',
id: 1
},
{
name: 'Name2',
id: 2
},
]
btnClick = () => {
let namePicker = Names[Math.floor(Math.random() * Names.length)]
Names.splice(Math.floor(Math.random() * Names.length), 1);
}

我该怎么做?

随机数必须计算一次,否则可以获得不同的索引。

const Names = [{
name: 'Name1',
id: 1
},
{
name: 'Name2',
id: 2
},
];
let rnd = Math.floor(Math.random() * Names.length);
let namePicker = Names[rnd];
Names.splice(rnd, 1);
console.log('picked ', namePicker);
console.log('Array  ', Names)

最新更新