简体   繁体   English

包含另一个文件中的数组(nodejs)

[英]Include an array from another file (nodejs)

I have a file which contains code to iterate over a very large array. 我有一个文件,其中包含要在非常大的数组上进行迭代的代码。 I'd rather not have the array in the same file as the code to keep things clean. 我宁愿不要将数组与代码保持在同一文件中,以保持环境整洁。 However, I'm not sure how to include the file which contains my array and properly access the individual elements for my iteration. 但是,我不确定如何包括包含数组的文件,以及如何正确地访问各个元素以进行迭代。 I'd rather not use a JSON object because I don't need key -> value . 我宁愿不使用JSON对象,因为我不需要key -> value

Like everyone else is saying, you can use require and put the function into the exports : 就像其他人说的那样,您可以使用require并将函数放入exports

myOtherFile.js myOtherFile.js

exports.largeArrayFunction = function() {
     //do stuff
     return stuff;
}

myMainNodeFile.js myMainNodeFile.js

var otherFile = require("myOtherFile.js");
var myArray = otherFile.largeArrayFunction();

Either use a regular JavaScript file: 使用常规的JavaScript文件:

module.exports = [1, 2, 3]

Or a JSON file, which can also be a simple Array: 或JSON文件,也可以是简单的Array:

[1, 2, 3]

Then include it using require: 然后使用require包括它:

var arr = require('./array.js'); // Or './array.json'

for(var i = 0; i < arr.length; i++) {
    // arr[i] ...
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM