2016-03-08 34 views
-1

我想創建一個)存儲一些詞在一個文檔(JSON,因爲我與Couchbase工作的系統)和B),然後選擇這些字一個隨機數生成Node JS - 如何存儲單詞並訪問它們?

現在我有一些問題:

1-應該怎麼存儲這些字(在單個文件或單獨)

2-我應該如何給每一個的索引,所以我可以訪問它們?有沒有這個模塊?

三是有產生隨機數的模塊,或者我需要做的是,在純JS

我做了一些研究工作,但我願意接受更好的ways.thanks

回答

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' 
0

您可以創建一個詞對象來處理這個給你,具體如下:

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像上面的數組索引。如果你的意思是另一種索引,那麼卡爾文的答案提供了一種通過對象進行索引的不同方法。

相關問題