随机选择对象

Randomly select objects

本文关键字:对象 选择 随机      更新时间:2023-09-26

我的目标是根据对这个问题无关紧要的几个参数获得一个随机对象。

function CreateObject(name) = {
this.name = name
};
var bob = CreateObject("Bob");
var john = CreateObject("John");
var rob = CreateObject("Rob");
var steven = CreateObject("Steven");

我是否需要将每个对象插入到数组中,或者如果我有 100+ 个对象,是否有更好的方法?

如果这些对象已创建但从未销毁,则可以让构造函数为您维护一个数组,并将随机函数挂接到其中:

var CreateObject = (function() {
    var created = [];
    var CreateObject = function(name) {
        this.name = name;
        created.push(this);
    };
    CreateObject.random = function() {
        return created[Math.floor(created.length * Math.random())];
    }
    return CreateObject;
}())
var bob = new CreateObject("Bob");
var john = new CreateObject("John");
var rob = new CreateObject("Rob");
var steven = new CreateObject("Steven");
CreateObject.random();  // CreateObject {name: "Rob"}
CreateObject.random();  // CreateObject {name: "Steven"}
CreateObject.random();  // CreateObject {name: "Rob"}
CreateObject.random();  // CreateObject {name: "John"}
// etc.

也可以扩展此技术以允许删除,但您必须以某种方式显式告诉构造函数正在删除对象。 否则,您的随机函数不仅无法正常工作,而且还会出现内存泄漏。

(请注意,存储数组的并不完全是构造函数。 它存储在构造函数有权访问的闭包中。

最常用、最简单和最高效的解决方案是将所有内容存储在数组中,然后选取一个随机索引。