简体   繁体   English

如何使用slice方法从数组中获取随机元素并将其存储

[英]how to use the slice method to take a random element from an array and store it

I have an array lets say array x = A,B,C,D,E 我有一个数组可以说array x = A,B,C,D,E

I want to use the slice function to take a random element from my array and store it for later use in a new var 我想使用slice函数从数组中获取随机元素,并将其存储以供以后在新的var中使用

so I get a new variable ie var y= x.slice 所以我得到一个新变量,即var y= x.slice

But I do not want to specify which element it takes from the array, I want it to be random each time how do I randomize the slice ? 但是我不想指定它从数组中获取哪个元素,我希望每次如何随机化切片时它都是随机的?

use splice() to extract and remove an element from an array. 使用splice()从数组中提取和删除元素。

Use Math.random() to generate a random number from 0 to 1 使用Math.random()生成一个从0到1的随机数

multiply by the number of elements or length of the array 乘以元素数或数组length

and trucate with Math.floor() the result to get a random index into the array. 并使用Math.floor()遍历结果以获取数组的随机索引。

var x = ['a','b','c','d']; 
var y = x.splice(Math.floor(Math.random()*x.length),1);

now, y contains the new array of the single element that has been extracted, and x contains the array of the remaining elements. 现在, y包含已提取的单个元素的新数组, x包含其余元素的数组。

if instead of an array you just want the element returned, change that line to 如果只希望元素返回而不是数组,则将该行更改为

var y = x.splice(Math.floor(Math.random()*x.length),1)[0];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM