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

4

我正在尝试从module.export数组中检索值,但我无法做到。你能帮我吗?

这是words.js文件

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

在 main.js 文件中,我正在调用:

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

现在,我该如何检索words.js中的值以在main.js中使用?
我的意思是,如果我想要获取一个随机数[3],然后显示相应的值[phrase4]?
这就是我尝试做的事情,但完全没有起作用。
var factIndex = Math.floor(Math.random() * recipes.length);
var randomFact = recipes[factIndex];

请帮忙。

谢谢!

3个回答

3
您可以使用对象键数组Object.keys()或对象条目数组Object.entries()从对象中检索随机属性值。

Object.keys():

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

console.log(randomFact);

Object.entries():

const recipes = {"word1": 'phrase1', "word2": 'phrase2', "word3": 'phrase3', "word4": 'phrase4', "word5": 'phrase5'},
  recipesEntries = Object.entries(recipes),
  factIndex = Math.floor(Math.random() * recipesEntries.length),
  randomFact = recipesEntries[factIndex][1];

console.log(randomFact);


我曾经遇到过完全相同的问题,但是通过这个解决方案,我成功地解决了它。然而,我不明白它是如何将 [{"word1":"phrase1","word2":"phrase2", "word3":"phrase3"}] 转换成一个数组的。如果您能够解释一下,我将不胜感激。 - Umar Aftab
@UmarAftab 你可以使用 Object.entries() - Yosvel Quintero

3
你应该考虑导出一个数组。 例如,像这样:
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');

谢谢@JoschuaSchneider,但是有人刚刚发布了完全相同的答案。这个看起来也很好,但我真的需要使用对象数组。 - spaceman
没问题,但你本可以修改我的代码以导出一个对象数组。这样可以避免使用Object.keys()循环等操作。 - Joschua Schneider

0
据我所知,module.exports 适用于函数。一个模块是一个容器,可以在另一个文件中调用其中的函数。
你想要的是存储字符串列表并遍历其内容。我建议使用数组,这将让您通过循环或使用随机数[3]访问值,或者创建一个json文件。

嘿,@Alexander Luna,有人刚刚发布了完全正确的答案。看一下,你就会知道我在找什么了。感谢关注! - spaceman

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接