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

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中定义lorem参数,该参数本质上是lorem调用中的getRandomElement对象本身?我可以在调用arguments摆脱其第一个元素并在其后传递参数之前,对apply对象做些什么吗?

最佳答案

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


是的,slice这样做:

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

10-06 04:38