简体   繁体   English

从关联数组中选择一个随机数组元素

[英]Picking a random array element from an associative array

How would I pick a random array element from an associative array with regards to array length ? 关于数组长度,我如何从关联数组中选择随机数组元素?

For example: 例如:

actors[name]=firstname
movielist[title]=[director,artwork,actors]

If I wanted to pull out a single random array element and all the information it from it then how would I achieve this? 如果我想提取单个随机数组元素及其中的所有信息,那我将如何实现呢?

Assuming by "associative array" you mean a JavaScript object (which has zero or more key/value properties), you can do something like the following, which selects a property at random and returns its name: 假设“关联数组”是指一个JavaScript对象(具有零个或多个键/值属性),则可以执行以下操作,该操作随机选择一个属性并返回其名称:

function getRandomObjectPropertyName(obj) {
   var a = [],
       k;

   for (k in obj)
      if (obj.hasOwnProperty(k)
         a.push(k);

   if (a.length === 0)
      return null; // or whatever default return you want for an empty object

   return a[Math.floor(Math.random() * a.length)];

   // or to return the actual value associated with the key:
   return obj[ a[Math.floor(Math.random() * a.length)] ];
}

In case it's not clear how the above works, it copies all of the key names from the object into an array. 如果不清楚上面的工作方式,它将所有键名从对象复制到数组中。 Use of .hasOwnProperty() is (arguably) optional depending on your needs. .hasOwnProperty()使用(可以说)是可选的,具体取决于您的需求。 Because the array has a length and numerically indexed items you can then use the Math functions to select an item randomly. 由于数组具有长度和数字索引项目,因此您可以使用数学函数随机选择一个项目。

Once you have the randomly selected key name you can use it to access the value of that property. 拥有随机选择的键名称后,就可以使用它来访问该属性的值。 Or (as shown above) you could change the function to return the actual value. 或者(如上所示),您可以更改函数以返回实际值。 Or (not shown, but trivial) change the function to return both key and value as a new object. 或者(未显示,但比较琐碎)更改功能以将键和值都作为新对象返回。 Up to you. 由你决定。

It's kind of unclear from your question what your datastructure is, but assuming movielist is an object where each property has a key name that is the movie title and an associated property that is an array containing the director, artwork and a nested array of actors, then you can do this: 从您的问题中还不清楚您的数据结构是什么,但是假设movielist是一个对象,其中每个属性的键名都是电影标题,而相关的属性是一个数组,其中包含导演,插图和演员的嵌套数组,那么您可以执行以下操作:

var randomMovieTitle = getRandomObjectPropertyName(movielist);
// randomMovieTitle might be, say, "Back to the future"

// you could then get the list of actors associated with the movie like so:
var actorsFromRandomMovie = movielist[randomMovieTitle][2];

// or get the director:
alert(movielist[randomMovieTitle][0]); // "Robert Zemeckis"

EDIT: If you don't care about older browsers you can use Object.keys() to get an array of all the key names and then randomly select from that. 编辑:如果您不关心较旧的浏览器,则可以使用Object.keys()获取所有键名的数组,然后从中随机选择。

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

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