문제

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.

도움이 되었습니까?

해결책 2

Like everyone else is saying, you can use require and put the function into the exports:

myOtherFile.js

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

myMainNodeFile.js

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

다른 팁

Either use a regular JavaScript file:

module.exports = [1, 2, 3]

Or a JSON file, which can also be a simple Array:

[1, 2, 3]

Then include it using require:

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

for(var i = 0; i < arr.length; i++) {
    // arr[i] ...
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top