One of the problems with teaching yourself how to code is that you miss some things that might be fairly simple:
I have written a function which takes text files (e.g. "someData1.txt", "someData2.txt" etc.) turns their contents into an array ("myArray"), and extracts their title as a variable ("fileName").
I am at the stage where I have parsed the filenames and the arrays, but I would like to rename each array with the variable, so that the first array becomes "someData1", and so on. I already have a bunch of code which will do various things with each different array, so it would useful if I could name them the way I wish.
I thought I could use valueOf to do it, as in
fileName.valueOf() = myArray;
but that does not work. So how do I do this?
Thanks!
-
1huh? I have no clue what the final outcome is supposed to be... And that is not how you use valueOfepascarello– epascarello2015年01月21日 22:25:56 +00:00Commented Jan 21, 2015 at 22:25
2 Answers 2
Probably the easiest way would be to use an object and then use array notation to assign keys to it. Let me show you:
var myObj = {};
myObj.someProperty = 1;
is the same as
myObj['someProperty'] = 1; // note the quotes
So, that makes possible to use variable names as keys. In your example:
var fileName = 'someData1';
var myObj = {};
myObj[fileName] = myArray; // myArray being file contents from your example
and now when you want to access the contents, you can simply do:
myObj.someData1
or:
myObj['someData1']
Just make sure you have no duplicate file names and you're good to go.
Comments
What you want to do is defining a variable name dynamically.
It is not possible in Javascript though, but you can be tricky. You have then two options :
- Use the global scope object to store your variables (not a good practice) :
global[variableName] = array;
And then you will be able to access it in the scope :
global['toto'] = 42;
console.log(toto);
=> 42
This is NOT a good practice but is the only way to define a variable in the scope dynamically.
- Use an object to store it :
var myArrays = [];
myArrays[variableName] = array;
In each case you define in fact a property of an object.
You have to keep in mind that :
myArrays['toto'] = 42;
is the same that :
myArrays.toto = 42;
So to access your array, just do :
myArrays.toto
6 Comments
global (source). If you assign a value to a variable that does not have a functionally scoped var then it will be hoisted to the global scope.global object, but it is the only solution to have a variable literally defined in scope, not as a property of an object.global refers to the global scope in Node.js, very much like window in web browsers. PS. If I need to set global vars I wrap my code in (function(global){ ... }(this)) so I don't have to care how to reference the global scope in given environment.