How do I create a dynamic variable in Javascript?
For example, I have:
var myAwesomeText = "Hello World!"
But now I want the varible MyAesomeText to have a random number attached to it every time the page is refreshed. So it would instead look like something like this:
var myAwesomeText12345 = "Hello World!"
And most importantly, how do I call that that new random variable back once the random number has been assigned to it? (i.e: alert(???);)
I've tried something like this, but I'm going wrong with this somewhere.
var myRnd = Math.floor(Math.random()*100000);
var myVar = "MyAwesomeText" + myRnd;
str = myVar + ' = ' + '"Hello World!"';
eval(str);
alert(str);
You can access the variable via the window object:
var myRnd = Math.floor(Math.random()*100000);
var myVar = "MyAwesomeText" + myRnd;
window[myVar] = "Hello World!";
alert(window[myVar]);
Don't use eval for this: it is slower and completely unnecessary for this problem. Also it can have unexpected side-effects if your MyAwesomeText has characters in it that have special meaning in JavaScript code, such as brackets, semi-colon, colon, comma, braces, ... etc.
Note that the notation object['prop'] gives the same result as object.prop. Since global variables are created in the window object, you can access any variable via the window.myvariable notation.
Combining these two facts, you can access global variables that have a dynamic name with window[dynamicVariableName].
eval is the way to go
var num = 10;
var string = "var a"+num +"= 'hi'"
string
// "var a10= 'hi'"
eval(string)
a10
// 'hi'
You miss one eval on the alert
var myRnd = Math.floor(Math.random()*100000);
var myVar = "MyAwesomeText" + myRnd;
str = myVar + ' = ' + '"Hello World!"';
eval(str);
alert(eval(myVar));
Related
Everything I'm reading about modifying strings in Javascript says that strings are immutable. Hence why concat returns a new string that is a modification of the original:
let originalString = 'hello';
let modifiedString = originalString.concat(' world');
console.log('originalString:', originalString);
console.log('modifiedString:', modifiedString);
results in:
"originalString: hello"
"modifiedString: hello world"
So far it makes sense. The original string remains even after concat because strings are immutable.
However, if I do the following:
let originalString2 = 'hello';
let modifiedString2 = originalString2 += ' world';
console.log('originalString2:', originalString2);
console.log('modifiedString2:', modifiedString2)
the result is:
"originalString2: hello world"
"modifiedString2: hello world"
This sure seems like it's mutating the original string to me. If that is not what's happening, can someone explain it to me? I've even found articles that go over the ways to modify strings that say at the beginning "Javascript strings are immutable" and later go on to say that the += method is mutating the original string, so I'm getting contradictory information.
JSFiddle of the simple test
I think it's because of the short hand addition operator (+=) you're using.
It's actually doing 2 operations first addition then assignment.
let x = 2;
x += 2;
// The above line is equivalent to the following.
x = x + 2;
So for you're example
let str = "hello";
str += "world"; // is the same as
str = str + "world";
So we are making a new string by str + "world" then assigning it to our str variable. So it's still immutable :)
I'm working with a JS script that someone developed for me but I need to convert it to AS3. I'm good with AS3 but a bit baffled re: how to translate these two lines into AS3.
var teams = Array.apply(null, {length: numOfTeams}).map(Number.call, Number)
the following snippet with backwards single quotes
pairs[`${i},${x}`] = true;
Although the script runs fine in a JS interpreter, I'm not sure what "`" denotes and I'm thinking that "apply" and "map" may have been around in AS2 when it was prototype-based but I never used AS2. Suggestions?
So in modern JS the back tick represents string interpolation. I don't think there is an equivalent in AS3. Inside back ticks you can use ${} to wrap a variable in a string.
Taking the example and imagining some input
var i = 1;
var x = 2;
`${i},${x}`
// outputs "1,2" as a string
var i = "Foo";
var x = "Bar";
`${i},${x}`
// outputs "Foo,Bar" as a string
It just concatenates two variables with a comma in between.
It could be written the same way.
var i = 1;
var x = 2;
i + "," + x
// outputs "1,2" as a string
It reads like you have an Object pairs with i comma x as a key and boolean as a value.
{
"1,2": true,
"0,0": false,
"4,5": true,
"9,3": true
}
`` denotes a template literal, which means that ${i},${x} will be replaced with whatever the variable i contains, a comma, and then whatever the variable x contains. The following two are equivalent:
pairs = {};
i = 'hello'
x = 'world'
pairs[`${i},${x}`] = true;
console.log(pairs)
pairs = {}
pairs[i + ',' + x] = true
console.log(pairs)
.apply looks like it existed in AS3, as does .map
I can take value of a span with this code:
document.getElementById("aaa:j_idt89:0:asd").innerHTML
but I want to use variable like i=1, for example like this:
i=1
document.getElementById("aaa:j_idt89:'[i]':asd").innerHTML
but it gives an error. How can I use the i variable in the string?
Use this code
document.getElementById("aaa:j_idt89:"+ i +":asd").innerHTML
Note the change I made inside. "+ i +" . You actually needed a String Concatenation.
So explaining the code.
when i = 1
"aaa:j_idt89:"+ i +":asd" = "aaa:j_idt89:"+ 1 +":asd" = "aaa:j_idt89:1:asd" = thats what you need
This should work for you:
var i = 1;
var element = document.getElementById("aaa:j_idt89:" + i + ":asd").innerHTML
you need to build your string up and to use your variable you need to concatenate it to your string like above " + i + " and it will work.
I have following string var foo = require('foo/bar'); which I want to change to var foo = require('../../foo/bar');.
So far I wrote following code which would do this:
var search = 'foo/bar';
var replace = '../../foo/bar';
var regex = new RegExp('require[(](\"|\')' + search + '(\"|\')[)]', 'g');
var source = 'var foo = require(\'foo/bar\')';
source.replace(regex, 'require(\'' + replace + '\')');
However as you see this is very inefficient. What could I do to make this regex a bit shorter. For example:
only have to replace the path and not to rewrite require with require(\'' + replace + '\')'
make (\"|\') and [(] shorter
anything else?
Best,
Bo
Edit:
I am doing this replacement on complete javascript source files.
Edit2:
What is necessary to change var foobar = require('foo/bar'); to var foobar = require('../../foo/baz/bar') when foo/ and ../../foo/baz/ should be variable?
You can use this code:
var search = 'foo/bar';
var source = "var foo = require('foo/bar')";
var regex = new RegExp('(require)\\((["\'])(' + search + ')\\2\\)', 'g');
var repl = source.replace(regex, "$1('../../$3')");
//=> var foo = require('../../foo/bar')
Here is an alternative :
var str = "var foo = require('foo/bar');";
str = str.split(/(')/);
str.splice(2, 0, '../../');
str = str.join('');
Even simpler :
"var foo = require('foo/bar');".replace(/'([^']+)'/, "'../../$1'")
I wonder if you could do the replacement before wrapping your path inside the var xxx = require() statement.
Optimizing code that starts by undoing what has been done just before seems a bit inefficient.
Besides, it seems you already know the target path (foo/bar in your example), but it is not even necessary to use that.
The regexp here boils down to splitting the string after the opening quote and inserting the ../../ prefix.
You could do that with
source = source.split(/["']/,2).join('"../../')+'");';
The regexp is a constant, so you could put it into a variable to have it compiled once and for all.
That would probably be more efficient than generating and recompiling the regexp from your example each time.
But anyway, I wonder how many such strings you would have to replace to start noticing a performance hit.
I have this string which I want to convert to an array:
var test = "{href:'one'},{href:'two'}";
So how can I convert this to an array?:
var new = [{href:'one'},{href:'two'}];
It depends where you got it from..
If possible you should correct it a bit to make it valid JSON syntax (at least in terms of the quotes)
var test = '{"href":"one"},{"href":"two"}';
var arr = JSON.parse('[' + test + ']');
Notice the " around both keys and values.
(making directly var test = '[{"href":"one"},{"href":"two"}]'; is even better)
If you could modify the original string to be valid JSON then you could do this:
JSON.parse(test)
Valid JSON:
var test = '[{"href":"one"},{"href":"two"}]';
Using jQuery:
var str = '{"id":1,"name":"Test1"},{"id":2,"name":"Test2"}';
var jsonObj = $.parseJSON('[' + str + ']');
jsonObj is your JSON object.
If changing the string to be valid JSON is not an option, and you fully trust this string, and its origin then I would use eval:
var test = "{href:'one'},{href:'two'}";
var arr = eval("[" + test + "]");
On that last note, please be aware that, if this string is coming from the user, it would be possible for them to pass in malicious code that eval will happily execute.
As an extremely trivial example, consider this
var test = "(function(){ window.jQuery = undefined; })()";
var arr = eval("[" + test + "]");
Bam, jQuery is wiped out.
Demonstrated here