This question already has answers here:
How do I create dynamic variable names inside a loop?
(8 answers)
Create dynamic variable names based on count result
(3 answers)
Closed 3 months ago.
I am trying to create dynamic variables using Window. The exact thing I want to do is working fine with eval. But as you may know, that’s not advised.
Some examples.
I may define some variables like this.
var word1 = The;
var word2 = Number;
var word3 = Is;
var number = 100;
Now I combine them.
var phrase = word1+word2+word3+number.
If I use the window keyword in front of the phrase variable, then it will work, provided it is at the beginning of the line of code. However, if I try to put window in front of a variable in the middle of a line of code, it doesn’t work. However, eval does work. Example below.
window[phrase]
That will work.
But if it’s something like this
window[newCombinedVariable] = document.querySelector(window[newCombinedVariable2])
That will not work.
However, this will work.
window[newCombinedVariable] = document.querySelector(eval(newCombinedVariable2))
So, window can take a combination of strings with dynamic variables and it works at the beginning, but not in the middle, such as after doc/query selector. But eval works fine that way when using the exact same combined variables.
Can someone suggest what I must do in order for window to give me the same results as eval?
Related
This question already has answers here:
Set document.getElementById to variable
(5 answers)
Closed 5 years ago.
I have this habit of using function id(_id) { return document.getElementById(_id); } as to lessen the work of typing this over and over.
sidenote:
jquery becomes too heavy for small tasks and projects
As I learnt Javascript more I came to know that we can pass around functions just like objects so we can do
var id = document.getElementById;
It seems like both do the exact same thing. However, I am not an expert in Javascript, so could there be any difference internally? and which is the preferred way of using?
Yes, the context is:
const log = console.log;
log("test");
The upper wont work because the context changed, and log must be called on a console object, not on window ( aka without context). However, there are easy workarounds:
const log = console.log.bind(console);
Or you use functions, for example the arrow ones:
const log = (...args) => console.log(...args);
This question already has an answer here:
Can't get global variables inside the function (javascript)
(1 answer)
Closed 8 years ago.
Well, after much head scratching this afternoon; I came to realize why my array was coming back as undefined. Despite the word 'closed' not being a reserved JS word; it seems it is some kind of reserved word elsewhere and so an array cannot be called 'closed'.
My question is this; if Javascript isn't reserving this word - what is? The browser? The OS? I read that one should avoid using it as a naming convention for variables / objects but I don't understand what else is trying to use it.
Any insight would be much appreciated.
<html>
<head>
</head>
<body>
<script>
var greatArray = [];
var closed = [];
alert(greatArray.length);
alert(closed.length);
</script>
</body>
</html>
It's not so much that Javascript has reserved it as that it is reserved because of where Javascript is used. Consider this:
if (myWindow.closed)
Therefore, using closed as a name for a global variable must be avoided. You can use it as a local variable, though.
As mentioned by T.J. Crowder:
It's a predefined property on window that you can't redefine, and since all properties on window are globals
This question already has answers here:
javascript variable swapping using arrays
(3 answers)
Closed 8 years ago.
Saw in a single source next:
[param_o,param_got] = [param_got,param_o];
This code swap variables param_o & param_got.But how [param_o,param_got] = [param_got,param_o] works, if [] is new instance of Array in Javascript ?
EDIT
Try checking:
var param_o = 1;
var param_got = 2;
[param_o,param_got] = [param_got,param_o];
console.log(param_o+" "+param_got);
// 2 1
This notation is called destructuring assignment and is part of Javascript 1.7:
Destructuring assignment makes it possible to extract data from arrays
or objects using a syntax that mirrors the construction of array and
object literals.
The object and array literal expressions provide an easy way to create
ad-hoc packages of data. Once you've created these packages of data,
you can use them any way you want to. You can even return them from
functions.
One particularly useful thing you can do with destructuring assignment
is to read an entire structure in a single statement.
The first sample actually demonstrates explicitly that this is useful to avoid temporary variables as in your code sample.
Firefox has supported this feature since Firefox 2 already. For Chrome the bug is still open after 3 years. IE11 doesn't support it either from what I've just tested.
This question already has answers here:
What does 'var that = this;' mean in JavaScript?
(6 answers)
Closed 9 years ago.
I came across this many times in a new code base that I'm looking at and was wondering is there is any proper reasoning behind it?
You can use var that = this; is order to keep a reference to current this object, when later this will be pointing to something else.
Example (taken from here):
$('#element').click(function(){
// this is a reference to the element clicked on
var that = this;
$('.elements').each(function(){
// this is a reference to the current element in the loop
// that is still a reference to the element clicked on
});
});
Sometimes the meaning of this in JavaScript changes based on the scope. this inside of a constructor means something different than this inside of a function. Here's a good article about it.
If you want access to "this" outside/inside of the scope of a specific function call where what "this" is may have changed. Just one example I can think of.
This question already has answers here:
Why does a RegExp with global flag give wrong results?
(7 answers)
Closed 6 years ago.
Can anyone explain why the alert() in the following JavaScript code is firing? It appears to be a bug in the RegExp.test() method which reverses its previous decision each time you run the method. I'm using IE7.
I've found a replacement that appears solid, using the string.search(regex) method instead. But, I'm curious whether anyone knows something about this.
var styleHasWidthRegex = /\bwidth\s*\:/ig;
var styleText = "WIDTH: 350px";
var result1 = styleHasWidthRegex.test(styleText);
var result2 = !styleHasWidthRegex.test(styleText);
if (result1 == result2) {
alert("This should never happen!");
}
Your regex has the global (g) flag set. Every time it is executed, it'll update an internal index (the lastIndex property) specifying where it left off, and begin searching at that point the next time through.
Of course, you don't really want that - you want it to start at the beginning every time. So ditch the g flag.
See also: Inconsistent javascript logic behavior
In this scenario, you should be needing a global tag anyways, since in css declarations a property should only be declared once.