我想创建一个)存储一些词在一个文档(JSON,因为我与Couchbase工作的系统)和B),然后选择这些字一个随机数生成Node JS - 如何存储单词并访问它们?
现在我有一些问题:
1-应该怎么存储这些字(在单个文件或单独)
2-我应该如何给每一个的索引,所以我可以访问它们?有没有这个模块?
三是有产生随机数的模块,或者我需要做的是,在纯JS
我做了一些研究工作,但我愿意接受更好的ways.thanks
我想创建一个)存储一些词在一个文档(JSON,因为我与Couchbase工作的系统)和B),然后选择这些字一个随机数生成Node JS - 如何存储单词并访问它们?
现在我有一些问题:
1-应该怎么存储这些字(在单个文件或单独)
2-我应该如何给每一个的索引,所以我可以访问它们?有没有这个模块?
三是有产生随机数的模块,或者我需要做的是,在纯JS
我做了一些研究工作,但我愿意接受更好的ways.thanks
你可以存储包含所有单词的数组,并追踪每个单词的索引。下面的代码示例可能让你在正确的轨道上,但是,它没有进行测试,可能包含错误:
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'
您可以创建一个词对象来处理这个给你,具体如下:
function Words() {
// Array to store the words.
var wordList = [];
// Adds a word to the list, returns its index.
function addWord (newWord) {
return wordList.push(newWord) - 1;
}
// Adds an array of words to the list, returns the index of the first added.
function addWords (newWords) {
wordList = wordList.concat(newWords);
return wordList.length - newWords.length;
}
// Gets the words as a javascript object.
function asObject() {
return { words: wordList };
}
// Gets the words as a JSON string.
function asJson() {
listObject = asObject();
return JSON.stringify(listObject);
}
// Retrieves a random word from the list.
function randomWord() {
var randomIndex = Math.floor(Math.random() * wordList.length);
return wordList[randomIndex];
}
return {
addWord: addWord,
addWords: addWords,
asObject: asObject,
asJson: asJson,
randomWord: randomWord,
get wordList() {
return wordList;
}
};
}
然后你可以添加单词,并根据需要通过做这样的访问它们:
var words = Words();
// Add words to the list.
var index = words.addWord('apple');
var firstIndex = words.addWords(['orange', 'pear', 'strawberry']);
// Retrieve a random word.
var random = words.randomWord();
// Retrieves the words in object or JSON format.
var wordObject = words.asObject();
var jsonWords = words.asJson();
// Access words by index.
var myWord = words.wordList[firstIndex]; // Returns 'orange'.
我不是100%,你的意思是访问每一个通过索引什么明确的,所以我认为somethi像上面的数组索引。如果你的意思是另一种索引,那么卡尔文的答案提供了一种通过对象进行索引的不同方法。