【发布时间】:2016-06-06 10:06:18
【问题描述】:
我有两个 json 文件,list1.json 和 list2.json,我设法将它们连接起来,但我有两个角色:
结果列表应该只包含来自list1.json 的10 个随机项目,来自list2.json 的所有项目,然后我应该在页面上以随机顺序显示它们。
我该怎么做?
【问题讨论】:
标签: javascript json vue.js
我有两个 json 文件,list1.json 和 list2.json,我设法将它们连接起来,但我有两个角色:
结果列表应该只包含来自list1.json 的10 个随机项目,来自list2.json 的所有项目,然后我应该在页面上以随机顺序显示它们。
我该怎么做?
【问题讨论】:
标签: javascript json vue.js
你可以使用 lodash 来完成这个任务。
_.sampleSize(list1.json, 10)会给你十个随机物品,
然后_.concat(_.sampleSize(list1.json, 10), list2.json) 会给你想要的结果。
获得包含所需项目的列表后,您可以使用_.shuffle 函数随机排列其顺序。
您可以在这里阅读更多内容: https://lodash.com/docs#sampleSize 和 https://lodash.com/docs#concat
当然,这两个函数都适用于 JavaScript 数组而不是文件,您必须先读取/请求这些文件并解析它们。
【讨论】:
使用纯 javascript 的解决方案(但我建议也使用下划线或 lodash,正如 Gilad Artzi 所说)。
function array_random_idx(arr) {
var idx = parseInt(Math.random() * arr.length);
return idx;
}
function remove_random(arr) {
var idx = array_random_idx(arr);
return arr.splice(idx, 1)[0];
}
function array_shuffle(a) {
var j, x, i;
for (i = a.length; i; i -= 1) {
j = Math.floor(Math.random() * i);
x = a[i - 1];
a[i - 1] = a[j];
a[j] = x;
}
}
var result1 = []
for (var i = 0; i < 10; i++) {
var elem = remove_random(list1.json);
result1.push(elem);
}
var result = result1.concat(list2.json);
array_shuffle(result);
console.log(result);
【讨论】: