在一个js文件中调用另一个js文件的内容
问题描述:在一个文件夹中,只有两个js文件,现在a.js中有一个数组,b.js想引用它
解决办法:本人用的是nodejs运行环境提供的exports和require来解决。
代码示例:
a.js
let array = [
{name:"jack", age:21},
{name:"rose", age:17},
{name:"mike", age:23},
{name:"jonny", age:9}
];
const num = 10;
function test() {
console.log('i am a function');
}
// 导出规则: module.exports = {..., ..., ...};
module.exports = {
test,
num,
array
};
b.js
// 导入规则: const {..., ..., ...} = require('...');
// const 也可以为let,var, require括号内是导出文件的路径
// 导出和导入{}里面的内容名称必须一致,顺序不作要求,导入文件也可根据需要导入相应的模块,不需要全部导入
const {num,test,array} = require('./a');
test();
console.log(array);

浙公网安备 33010602011771号