让我们假设我打算实现一个随机化功能,如下所示:
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.getRandomKey
和Randomizer.getRandomElement
,以便我可以避免在b
中定义一个基本为{{1}的lorem
参数在lorem
电话中对象本身?我可以在调用getRandomElement
之前对arguments
对象做些什么来摆脱它的第一个元素并在之后传递参数吗?
答案 0 :(得分:1)
我可以在调用
arguments
之前对apply
对象做些什么来摆脱它的第一个元素并在之后传递参数吗?
是的,slice
会这样做:
var slice = Array.prototype.slice;
….apply(this, slice.call(arguments, 1))