简体   繁体   中英

Export array to be used in another javascript file

In my post request, I want to check if thisString exists in another javascript file array.

Array.js

exports.names = [
    'John',
    'Mary'
]

Main.js

if (names.includes(thisString)) {
    ...do stuff...
}

if thisString = Mary , Main.js returns "undefined". If I console.log(names) it returns the array. But console.log(names[0]) is undefined. And If I copy and paste the array into the Main.js file it works as intended.

I want to have the array in another file just to clean things up a bit. But what am I doing wrong?

Typescript :

Array.ts

export let array = [1,2,3];

Main.ts

import {array} from "./Array.ts"
array.map(item => console.log(item +1))

Javascript (nodejs)

array.js

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

main.js

let module = require('./array.js');

let array = module.array;

array.map(item => console.log(item +1))

The below works for me. You could also try:

Array.js

exports.names = [
    'John',
    'Mary'
]

Main.js

const data = require('./array.js');

const thisString = 'Mary';
if (data && data.names && data.names.includes(thisString)) {
    console.log('You are in!');
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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