我有以下使用测试数据的 fiddle ,并且我正在使用 $.each 查找数据
我可以循环遍历没有问题,但我想循环遍历数据,然后从中随机获取3个对象。
任何提示或技巧都会有所帮助:
https://jsfiddle.net/inkedraskal/pah44qv6/
$.each(testData,function(x, blah){
//console.log(blah._id);
//this gets each objects id & picture, but I want to get 3 random objects, and their corresponding data
var activeValue = blah._id,
pictureValue = blah.picture;
var markUp = '';
markUp += activeValue + pictureValue;
console.log(markUp);
});
对于下面的问题,它们需要是唯一的**
最佳答案
下面代码片段中的函数获取一个数组和一些 (X) 项,并返回一个新数组,其中包含原始数组中的 X 个唯一随机项:
function getRandomItems(arr, items) {
var ret = [];
var indexes = [];
var arr_length = arr.length;
// If we don't have enough items to return - return the original array
if (arr_length < items) {
return arr;
}
while (ret.length < items) {
i = Math.floor(Math.random() * arr_length);
if (indexes.indexOf(i) == -1) {
indexes[indexes.length] = i;
ret[ret.length] = arr[i];
}
}
return ret;
}
arr = ['a', 'b', 'c', 'd', 'e']
console.log(getRandomItems(arr, 2))
如果您想在代码中的每个 Array
上使用该函数作为“ native ”函数,您还可以将该函数添加到 Array.prototype
中:
Array.prototype.getRandomItems = function(items) {
var ret = [];
var indexes = [];
var arr_length = this.length;
// If we don't have enough items to return - return the original array
if (arr_length < items) {
return this;
}
while (ret.length < items) {
i = Math.floor(Math.random() * arr_length);
if (indexes.indexOf(i) == -1) {
indexes[indexes.length] = i;
ret[ret.length] = this[i];
}
}
return ret;
}
arr1 = ['a', 'b', 'c', 'd', 'e']
arr2 = ['aaa', 'bbb', 'ccc', 'ddd', 'eee']
console.log(arr1.getRandomItems(1))
console.log(arr1.getRandomItems(2))
console.log(arr2.getRandomItems(3))
console.log(arr2.getRandomItems(4))
关于javascript - 在javascript中从数组中获取随机X个项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39671586/