如何实现一般集随机化器?

时间:2016-08-14 18:46:39

标签: javascript

让我们假设我打算实现一个随机化功能,如下所示:

function Randomizer() {
    //Get random member name of object
    Object.prototype.getRandomKey = function() {
        var keys = Object.keys(this);
        return keys[Math.floor(Math.random() * keys.length)];
    };
    //Get random member value of object
    Object.prototype.getRandomElement = function() {
        return this[this.getRandomKey()];
    };
    //Get random index of array
    Array.prototype.getRandomKey = function() {
        return Math.floor(Math.random() * this.length);
    };
    //Get random element of array
    Array.prototype.getRandomElement = function() {
        return this[this.getRandomKey()];
    };
    //Get random return key of function result
    Function.prototype.getRandomKey = function() {
        var result = this.apply(this, arguments);
        return result && result.getRandomKey();
    };
    //Get random return member of function result
    Function.prototype.getRandomElement = function() {
        var result = this.apply(this, arguments);
        return result && result.getRandomElement(result.getRandomKey());
    };
    //Get random element name of what if supported
    Randomizer.getRandomKey = function(what) {
        if ((!what) || (["undefined", "number", "boolean"].indexOf(typeof what) >= 0)) {
            //unsupported
        } else if (typeof what !== "function") {
            return what.getRandomKey(arguments);
        } else {
            return Randomizer.getRandomKey(what.apply(this, arguments));
        }
    };
    //Get random element value of what if supported
    Randomizer.getRandomElement = function(what) {
        if ((!what) || (["undefined", "number", "boolean"].indexOf(typeof what) >= 0)) {
            //unsupported
        } else if (typeof what !== "function") {
            return what.getRandomElement(arguments);
        } else {
            return Randomizer.getRandomElement(what.apply(this, arguments)); 
        }
    };
}

这是我初始化它的方式

Randomizer();

用法示例

function lorem(b, a) {
    return a.substring(1);
}
Randomizer.getRandomElement(lorem, "abcde");

我的问题如下:如何修改Randomizer.getRandomKeyRandomizer.getRandomElement,以便我可以避免在b中定义一个基本为{{1}的lorem参数在lorem电话中对象本身?我可以在调用getRandomElement之前对arguments对象做些什么来摆脱它的第一个元素并在之后传递参数吗?

1 个答案:

答案 0 :(得分:1)

  

我可以在调用arguments之前对apply对象做些什么来摆脱它的第一个元素并在之后传递参数吗?

是的,slice会这样做:

var slice = Array.prototype.slice;
….apply(this, slice.call(arguments, 1))