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

时间:2016-12-09 07:53:17

标签: javascript node.js lambda

我正在尝试从这个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],那么显示各自的值[phrase4]?

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

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

请帮忙。

谢谢!

3 个答案:

答案 0 :(得分:0)

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

您想要的是存储字符串列表并迭代其内容。我建议使用一个数组,它可以让你循环或使用随机数[3]访问值或创建一个json文件。

答案 1 :(得分:0)

您应该考虑导出数组。 像这样举例如:

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');

答案 2 :(得分:0)

您可以使用键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]];

<强>演示

&#13;
&#13;
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);
&#13;
&#13;
&#13;

相关问题