I am searching through existing data in Js through a variable, I found that maybe I can access the data through window["variable_name"] , but Js can't find the variable.
How am I going to access the data, or is there a better way to store the data and access it.
The data format
let info1=[{"id":0, "label":"XXX"},{"id":1, "label":"XXX"}, ...];
let info2=[{"id":0, "label":"XXX"},{"id":1, "label":"XXX"}, ...];
.
.
.
let info2000=[{"id":0, "label":"XXX"},{"id":1, "label":"XXX"}, ...];
Trying to access the variable
for (let i=1; i<=2000; i++) {
console.log(window["info"+i]);
}
You cant access the variable with window because you declared the variable with let. You need to use var to declare.
Variables declared by let are only available inside the block where they're defined. Variables declared by var are available throughout the function in which they're declared.
var info1=[{"id":0, "label":"XXX"},{"id":1, "label":"XXX"}];
var info2=[{"id":0, "label":"XXX"},{"id":1, "label":"XXX"}];
console.log(window["info1"]);
console.log(window["info2"]);
Related
I understand that it's not necessary to initialize variables, but what are the benefits of doing so? It doesn't effect the scope of the variable nor the data type. The only reasons I could find were:
Avoid resulting in "undefined"
Explicitly show what the variable is intended for i.e. let myArray = [];
How you define the variable does actually affect the scope of the variable.
There is a big difference between these statements as far as scope, and also as far as mutability for const:
x = 1;
var x = 1;
let x = 1;
const x = 1;
For instance, the first line will create a global variable, the second will create a function scoped variable, and the third line will create a block scoped variable.
Another difference is the concept of "hoisting". let and const do not "hoist".
Initializing variables provides an idea of the intended use (and intended data type).
https://www.w3schools.com/js/js_best_practices.asp
I have a list of variables:
subcatlist1 = 'aa';
subcatlist2 = 'bb';
subcatlist3 = 'cc';
What i would like to do, is insert the value of a given variable from the option options, into an element, but the 'number' of the variable (ie, 1, 2 or 3) is itself coming in as a variable, say itemNumber.
What I would like to do is:
$(element).html(subcatlist+ itemNumber);
... Which would give the value of aa for itemNumber = 1
The error that I am getting is:
ReferenceError: subcatlist is not defined - which make sense, because the variable subcatlist doesn't exist - only subcatlist1, subcatlist2, subcatlist3 exist.
Do how can i concatenate the subcatlist+ itemNumber to get a variable that i can use, as subcatlist1 etc?
Thanks
Use object instead of variable is better approach in your context,Because you concadenate with variable is wrong.
var subcatlist = {1:"aa",2:"bb",3:"cc"}
$(element).html(subcatlist[itemNumber]);
Updated
The solution is to access the needed variable as a property of the containing object.
If defined in the global scope using var , in javascript the value is assigned as a property of the global object, and it can be accessed using the self explanatory keyword globalThis
In JavaScript, there's always a global object defined. In a web browser, when scripts create global variables defined with the var keyword, they're created as members of the global object. (In Node.js this is not the case.)
var subcatlist1 = 'aa';
var subcatlist2 = 'bb';
var subcatlist3 = 'cc';
var itemNumber = parseInt(Math.random() * 3) + 1
$('#test').html(globalThis['subcatlist' + itemNumber])
<script
src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="test">
See also "Variable" variables in JavaScript
Original answer
If having a list of variables is mandatory you could use eval() like this:
$(element).html(eval("subcatlist"+ itemNumber));
eval can be harmful and should be avoided in most cases
I have a function with lots of variables and very big arrays being defined; this makes the function very large and hard to work with. How can I define the variables/arrays in another file and use them in this function?
Example:
DoStuff.js:
function genList(){
var listData = [
//lots of inner arrays and data
]
var dataItem = "value";//50 of these
//do stuff with the data
}
What I'm trying to do:
ExternalData.js:
var listData = [
//lots of inner arrays and data
]
var dataItem = "value";//50 of these
DoStuff.js:
function genList(){
//call variables/arrays from ExternalData.js
//do stuff
}
Note:
JQuery is applicable here, but I'd rather not call any other libraries for something so small.
I would define all the variables in an object for example:
var obj = {
array_one: ['x', 'y'],
some_value: 'z'
}
This method has the advantage of make a kind of namespace for all the variables, saving you from overriding values.
And then use that object into my code using some kind of include method.
One simple method could be to add the script before the one you are writing like this:
<script type="text/javascript" scr="file_with_object.js"></script>
Other more sophisticated but only advisable if you are going to repeat this kind of behavior
is to use a Library or a framework to make includes more concise, require.js is a good example
EDIT: In the previous example I used the object with var considering that the code was written on the global scope, I think it would be better to use window.obj = {} to ensure the variable is global. And, just for the record, any variable you define like this window.somevariable is going to be a global variable. Once you define a global variable you could use it anywhere in your code (after the definition takes place). The namespace is the right way to go though.
EDIT 2: I think this post is more about scope than includes. When you declare a variable this way: var some_variable; you are saying that you want to bind that variable to the current scope. So if you do that inside a function, that variable "lives" inside that function:
var some_var = 10;
function(){
var some_var = 5;
console.log(some_var) // 5
}
console.log(some_var) // 10
But if you declare the variable without the var on both cases you are making that varaible global the first time and overriding its value on the second:
some_var = 10;
function(){
some_var = 5;
console.log(some_var) // 5
}
console.log(some_var) // 5
And alway you declare a varaible without the var, that variable is accessible trough window.variablename, because you are not binding the variable to any particular scope, so the binding is made to the window objecy, which is the global scope "namespace".
I'm studying variable scope in Javascript, and have come across the difference between variable declaration, and variable initialization. From talking to a developer I know, my understanding is that writing var before a variable declaration assigns the variable to the local scope, while not writing var before declaring the variable assigns the variable to the global scope. Is this true?
If writing var before declaring a variable does assign the variable to the local scope, is it necessary to write var later, when initializing the variable to keep it in the local scope? For example:
var someVariable;
// Do some things with JavaScript
someVariable = 'Some Value'
Since I declared someVariable in the local scope with var, but then initialized someVariable without using var, does JavaScript think that I just initialized one variable in the local scope, or that I declared one variable in the local scope, and then declared and initialized another variable in the global scope?
Later on, when I want to change the value of someVariable again, do I need to write var before the variable expression, or will JavaScript know that I'm changing the value of an already declared local variable? Technically speaking, how does JavaScript know when I'm changing the value of an already declared local variable, and when I'm declaring and initializing a global variable?
var something = "Initial value."
This means: "create a variable in the local scope and give it an initial value". The local scope means the function in which you use this statement.
something = "New value."
This means: "find variable 'something' in the nearest scope, and assign it a new value".
If you use the second statement without ever using the first, the statement will look for any definition of something in progressively bigger scopes (the function that contains your function, if it exists, the function that contains that, etc., until it reaches the global scope). If it finds something, it will assign to an already existing variable. If it finds nothing, it will create a global variable with that name.
If you use var first, you simply ensure that this search always stops at local scope.
These are the same:
var x;
// ...
x = 1;
...and...
var x = 1;
Both define a variable in the local scope and assign a value to it. If you want to change the value of the variable later in the same scope you can simply reference it by name:
x = 2;
If you're in a different scope however, unless the variable was declared in the global scope in the first place you will not be able to access it (it's "out of scope"). Attempting to do so will define a variable with that name in the global scope.
function a(){
var x = 1;
}
function b(){
x = 2; // 'x' in a is out of scope, doing this declares a new 'x' in global scope
}
a();
b();
When referencing a variable in the same scope it was declared, you do not need to prefix it with var, though you can:
var x = 1;
// ...
var x = 2;
...there's no need to do that. While it assigns 2 to 'x', it logically has no effect since var is already in local scope. If x had been declared globally however:
var x = 1;
function a(){
var x = 2;
console.log(x);
}
a();
console.log(x);
This will print first '2' and then '1'. By referencing x preceded with var in the function, it applies the local scope to the variable. Once the function completes the variable's original scope is restored (or the re-scope is lost, if you want to look at it that way). Thanks to #zzzzBov for pointing this out.
Hope this helps.
my understanding is that writing var before a variable declaration assigns the variable to the local scope, while not writing var before declaring the variable assigns the variable to the global scope. Is this true?
Not entirely.
function foo() {
var a = 1;
function bar() {
a = 2; // Still in the scope of foo, not a global
}
}
Since I declared someVariable in the local scope with var, but then initialized someVariable without using var, does JavaScript think that I just initialized one variable in the local scope, or that I declared one variable in the local scope, and then declared and initialized another variable in the global scope?
There is only one someVariable in that example.
Later on, when I want to change the value of someVariable again, do I need to write var before the variable expression
var scopes a variable for the entire function, no matter where in the function it appears.
If you define a variable using var, you can refer to the same variable without using the var keyword over and over. These refer to the same variable:
var someVariable;
//...code...
someVariable = 'rawr';
If you did use the var keyword every time you were changing the variable, you wouldn't get separate variables. The newest declaration would just overwrite the oldest declaration. So there's no point in using the var keyword except for initialization. To change the value of someVariable, you can just make assignments to the variable name like in the above example.
Basically, using var will create a new variable if there is no variable in that scope with the same name.
Now take this code for example:
var someVariable = 'initialized';
function test1(){
//this someVariable will be a new variable since we have the var keyword and its in a different scope
var someVariable = 'test1';
console.log(someVariable);
}
function test2(){
//because there is no var keyword this refers to the someVariable in the parent scope
someVariable = 'test2';
console.log(someVariable);
}
console.log(someVariable); //initialized
test1(); //test1
console.log(someVariable); //initialized
test2(); //test2
console.log(someVariable); //test2
With this example you can see that depending on what you want the code to do, you could be having problems. If you wanted test2 to act like test1 and forgot to use the var keyword you would be confused when you were expecting someVariable to be initialized and instead it was test2.
But you could have also purposely not used the var keyword because you wanted test2 to update the parent variable. So it is important that you use the var keyword correctly.
Not using var when initializing variables will create the variable on the global scope. This is not good practice. If you want variables on the global scope, manually put them there. i.e. window.someVariable = 'initialize'; That way anyone else that sees your code knows that you made it a global variable on purpose.
At the top of json2.js (line 160 after the comments: https://github.com/douglascrockford/JSON-js/blob/master/json2.js), is the following code:
var JSON;
if (!JSON) {
JSON = {};
}
Typically, declaring var something will set "something" to undefined:
var something = {};
(function(){
var something;
console.log(something); // logs undefined
})();
Normally I would accomplish this goal by using:
var JSON = JSON || {};
So what's with the global JSON object that allows writing "var JSON" to not set it to undefined?
And why on earth would someone like Crockford promote a technique, that, in any other situation, would NOT operate like this?
It does this with any variable. Declaring it in the same scope again won't reset the value of the variable. I imagine it's a result of variable hoisting (all declarations are moved to the top of the function).
var a = 2;
var a;
console.log(a) // 2
In this specific case
var JSON;
if (!JSON) {
JSON = {};
}
and
var JSON = JSON || {};
are pretty much equivalent. It's just a matter of style preferences.
Now, if he had put it inside the self executing anonymous function, the local JSON would be set to undefined.
If you're asking why he's doing that, it's because he doesn't want to overwrite the native JSON object if it exists, but I think you knew that already.