我想创建一个系统A)在doc中存储一些单词(JSON,因为我使用Couchbase)和B)然后通过生成的随机数选择其中一个单词
现在我有一些问题:
1-我应该如何存储这些单词(在单个文档中或单独存储)
2-我应该如何给每个人一个索引,以便我可以访问它们?有这个模块吗?
3 - 是否有一个用于生成随机数的模块,或者我必须在纯JS中执行此操作
我为此做了一些研究,但我对更好的方式持开放态度。谢谢
答案 0 :(得分:0)
您可以存储所有单词的数组,并另外跟踪每个单词的索引。以下代码示例可能会使您走上正确的轨道,但是,它未经过测试并且可能包含错误:
function Dictionary() {
this.words = [];
this.indices = {};
}
function add(word) {
if (this.indices[word] == null) {
this.words.push(word);
this.indices[word] = this.words.length - 1;
}
}
function rand() {
var index = Math.floor(Math.random() * this.words.length);
return this.words[index];
}
Object.assign(Dictionary.prototype, { add, rand });
var dict = new Dictionary();
dict.add('cheese');
console.log(dict.rand());
// >> 'cheese'