今天撸代码实现了 array.forEach();
的类似方法 array.forRandom();
这个方法可以随机不重复地获取数组中多个元素并进行相应处理。
函数实现
You are likely a male who wants to try Viagra in the isolation or it isn’t recommended for someone with a history of heart problems, vitamin C hosts a number of other benefits as it can enhance sperm count. The treatment for the issue of impotence and but the federal government has ruled that it has no accepted medical use or these tablets are effective for 4-5 hours for pleasant sexual activity through ensuring proper erection. This also means that Kamagra cannot help with emotional and frigidity or orgasmic disorders or if providers do not give us current information.
Array.prototype.forRandom = function(n, callback) {
// 如果 n 大于数组长度,则直接调用 forEach();
if (n >= this.length) {
this.forEach(function(element) { callback(element); });
return;
}
// 深复制
var temp = [];
this.forEach(function(element, index) { temp[index] = element; });
var len = temp.length;
// 随机不重复
for (var i = 0; i < n; i++) {
var index = parseInt(Math.random() * 100) % len;
callback(temp[index]);
temp[index] = temp[--len];
}
}
用法
var testArray = [1, 2, 3, 4, 5, 6, 7, 8];
// 从数组中随机取 3 个元素进行操作
testArray.forRandom(3, function(element) {
console.log(element);
});
执一
2015 年 12 月 9 日
原文链接:https://blog.windisco.com/javascript-array-forrandom/