从module.exports对象数组中检索值

我试图从这个module.export数组中检索值,我只是不能。 你可以帮我吗?

这是words.js

module.exports = { "word1": 'phrase1', "word2": 'phrase2', "word3": 'phrase3', "word4": 'phrase4', "word5": 'phrase5' }; 

而在main.js我打电话

 var recipes = require('./words'); 

现在,我如何检索在main.js中使用的words.js的值

我的意思是,如果我想得到一个随机数[3],然后显示相应的值[短语4]?

这是我正在尝试做的,但它根本不起作用。

 var factIndex = Math.floor(Math.random() * recipes.length); var randomFact = recipes[factIndex]; 

请帮忙。

谢谢!

您可以使用Object数组的键Object.keys()从一个对象数组中检索一个随机属性值:

words.js

 module.exports = { "word1": 'phrase1', "word2": 'phrase2', "word3": 'phrase3', "word4": 'phrase4', "word5": 'phrase5' }; 

main.js

 var recipes = require('./words'), recipesKeysArr = Object.keys(recipes), factIndex = Math.floor(Math.random() * recipesKeysArr.length), randomFact = recipes[recipesKeysArr[factIndex]]; 

演示

 var recipes = {"word1": 'phrase1',"word2": 'phrase2',"word3": 'phrase3',"word4": 'phrase4',"word5": 'phrase5'}, recipesKeysArr = Object.keys(recipes), factIndex = Math.floor(Math.random() * recipesKeysArr.length), randomFact = recipes[recipesKeysArr[factIndex]]; console.log(randomFact); 

据我所知,module.exports是为了函数。 模块是您可以在另一个文件中调用的函数的容器。

你想要的是存储一个string列表并遍历它的内容。 我build议使用一个数组,它可以让你循环或访问使用随机数[3]值或创build一个json文件。

你应该考虑导出一个数组。 像这样的例子:

 module.exports = { words: ['phrase1','phrase2','phrase3',...] }; 

然后像这样使用它:

 var words = require('./path/to/file').words; //You can now loop it and you have a .length property words.map(function(word){ console.log(word) }) console.log(words.length) //getting a specific value is also done by the index: var myFirstPhrase = words[0]; 

或者如果你的文件只是导出那个单词列表,你甚至可以摆脱周围的对象并直接导出数组:

 module.exports = ['phrase1','phrase2', ...]; 

并像这样导入它:

 var words = require('./path/to/file');