admin管理员组

文章数量:1287632

//level1.js

[[1,2,3,0,0],
[0,0,0,4,0],
[0,4,2,0,0],
[0,0,0,0,0],
[0,0,1,3,0]];

I'm making a game and I want this array of arrays to be imported into my game.js file. (To be able to choose the map)

//game.js

let map = "level1"

import * as gameBoard from `./${map}.js`



//level1.js

[[1,2,3,0,0],
[0,0,0,4,0],
[0,4,2,0,0],
[0,0,0,0,0],
[0,0,1,3,0]];

I'm making a game and I want this array of arrays to be imported into my game.js file. (To be able to choose the map)

//game.js

let map = "level1"

import * as gameBoard from `./${map}.js`



Share Improve this question asked Oct 27, 2019 at 15:35 PettkoPettko 491 gold badge2 silver badges7 bronze badges 2
  • You are not exporting anything from level1.js. And I think that you can't use template strings for import statements. – VLAZ Commented Oct 27, 2019 at 15:36
  • @VLAZ so how should I do? – Pettko Commented Oct 27, 2019 at 15:37
Add a ment  | 

2 Answers 2

Reset to default 7

You need to export your array in level1.js.

  //level1.js

  export const array = [
    [1,2,3,0,0],
    [0,0,0,4,0],
    [0,4,2,0,0],
    [0,0,0,0,0],
    [0,0,1,3,0]
  ];

And then you can import the variable from game.js

//game.js
import { array } from './level1.js'

if you're running your scripts using "node script.js",then you're gonna have to use the "exports/require" method:

  • In level1.js:

exports.array = [1, 2, 3];

  • In game.js:

const level1 = require('./level1');
    
// then access it like so
console.log(level1.array);

If, however, you wanted to use the "import" syntax that the guys are suggesting above, then you're gonna have to enable ES6 syntax.

本文标签: In JavaScripthow to import an array from another javascript fileStack Overflow