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?
Implementation of Export in JavaScript Using the keyword “export” we can export anything like a variable, function, or class to any other file. What we have to do is, simply write the “export” keyword prior to that variable, function, class, or anything we want to export.
How to copy Array elements in JavaScript using concat() method. “concat()” is another useful JavaScript method that can assist you in copying array elements. In the concat() method, you can take an empty array and copy the original array elements to it. It will create a fresh copy of the specified array.
Because arrays in JS are reference values, so when you try to copy it using the = it will only copy the reference to the original array and not the value of the array. To create a real copy of an array, you need to copy over the value of the array under a new value variable.
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:
exports.names = [
'John',
'Mary'
]
const data = require('./array.js');
const thisString = 'Mary';
if (data && data.names && data.names.includes(thisString)) {
console.log('You are in!');
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With