I'm having some difficulty creating a variable with another variable in jQuery. I don't know how to write the var side of the equation. Here's what I'm trying to create:
var $counter= 0;
$('.selector').each(function(){
$counter += 1;
var newVariable-($counter) // this is where I'd like to create the new
// variable with the number from $counter at the end.
});
with the goal to creating:
newVariable-1
newVariable-2
newVariable-3...
and so on...
You could create an object to hold these values but not dynamic variables.
var $counter= 0;
var variableHolder = {};
$('.selector').each(function(){
$counter += 1;
variableHolder["newVariable-"+$counter] = ...
});
Or if you want to make global variables (which is not recommended), you could use window:
var $counter= 0;
$('.selector').each(function(){
$counter += 1;
window["newVariable-"+$counter] = ...
});
As others have pointed out, using an {} with square bracket notation will simplify this task greatly.
Something like this:
var myobj = {},
prefix = 'my_cool_var';
for(var i = 0, len = 10; i < len; i++) {
myobj[prefix + i] = undefined; // { my_cool_var + i : undefined }
}
// Setters - dot notation and square bracket
myobj.my_cool_var1 = "Hello!";
myobj['my_cool_var2'] = "Hello 2!";
// Getters - dot notation and square bracket
alert(myobj.my_cool_var1); // alerts Hello!
alert(myobj['my_cool_var2']); // alerts Hello 2!
Now, if you needed to expose the variables in a global scope (yuck - but hey, sometimes you gotta) so you don't need to specify an object (myobj), you can use window with square bracket notation in your for loop.
var prefix = 'my_global_var';
for(var i = 0, len = 10; i < len; i++) {
window[prefix + i] = undefined; // creates global, my_global_var + i = undefined
}
my_cool_var1 = "Hello!";
alert(my_cool_var1); // alerts Hello!
Finally, if you search the web deep enough, you'll find eval examples like this:
var prefix = 'my_evil_var';
for(var i = 0, len = 10; i < len; i++) {
// Don't do this. Use square bracket notation with window, if you need a global.
eval(prefix + i + '= undefined') // creates global, my_evil_var + i = undefined
}
my_evil_var = "Eval abuse is bad!!";
alert(my_evil_var1); // alerts Eval abuse is bad!!
Hope this helps!
Just make use of the json in this context,
var $counter= 0;
var $newVar = {};
$('.selector').each(function(){
$counter += 1;
$newVar['newVariable-'+ ($counter)] = null;
});
so you can access it like $newVar.newVariable-1,.. $newVar.newVariable-N And please note that this is the best practice, we could do as you asked by accessing the window object, but that is not recommended.
Related
I need to create dynamically name of variable with a loop .
example:
const1 = test;
const2 = test;
const3 = test;
....
I try this , but that only create 20 same variable name in array
I need a unique name increment by 1 at each loop and return each variable to use after.
function createVariables(){
var accounts = [];
for (var i = 0; i <= 20; ++i) {
accounts[i] = "whatever";
}
return accounts;
}
how can I do this ?
Using Object could be the work around
var accounts = {};
for (var i = 0; i <= 20; ++i) {
accounts["const"+i] = "test";
}
console.log(accounts)
If you need variable (not array), then you can use this code:
for (let i = 0; i <= 20; ++i) {
window[`whatever${i}`] = + i;
}
console.log(whatever0)
console.log(whatever1)
//...
console.log(whatever19)
See in playground: https://jsfiddle.net/denisstukalov/thvc2ew8/4/
What is it that you are trying to achieve? As mentioned in some of the comments, and array would be a better approach.
That said, one solution is to set values on a JavaScript object using string indexer (['']). See example below:
function createVariables(obj){
for (var i = 0; i <= 20; ++i) {
obj[`const${i}`] = "whatever";
}
}
// add it to a new object
const accounts = {};
createVariables(accounts);
console.log(accounts.const1, accounts.const2, accounts.const3);
// avoid adding it to global scope (like window)
createVariables(window);
console.log(const1, const2, const3);
There is something like this found in my javascript homework. Is this valid, or did they forget to put the braces?
var squares = [],
SIZE = 3,
EMPTY = " ",
score,
moves,
turn = "X";
There are 6 variables being declared in your code. It has nothing to do with an object.
squares is an array, size is a number (3), empty is a string ( ), score and moves are undefined and turn is a string (X)
Google javascript comma operator
EDIT: Declare variables used in scope
var doStuff = function() {
var i,
c = 2,
stuff = "stuff";
};
Rather than:
var doStuff = function() {
//some code
for( var i = 0; i <= 10; i++ ) {
//
}
//some code
var c = 2;
//some code
//some code
var stuff = "stuff";
};
As it lets developers see all the variables that are declared in that scope at a single glance, rather than having to search through the block to see what vars are being declared/used.
They didn't forget. Your teacher just didn't repeat the term 'var' for every variable.
That's the same as:
var squares = [];
var SIZE = 3;
var EMPTY = " ";
var score;
var moves;
var turn = "X";
I'm trying, but unsuccessfully, to get the value of a variable, where the variable name is dynamic
var v_1playerName = document.getElementById("id_1playerName").value;
var v_2playerName = document.getElementById("id_2playerName").value;
for (i = 1; i <=5 i++) {
alert(window["v_"+i+"playerName"]);
}
Is this possible?
A simple thing would be to put the variables in an array and then use the for loop to show them.
var v_1playerName = document.getElementById("id_1playerName").value;
var v_2playerName = document.getElementById("id_2playerName").value;
var nameArray = [v_1playerName,v_2playerName];
for (var i = 0; i < 5; i++) {
alert(nameArray[i]);
}
Accessing variables through window isn't a great idea.
Just store the values in an object and access them using square notation:
var obj = {
v_1playerName: 0,
v_2playerName: 3
}
obj['v_' + 2 + 'playerName']; // 3
If you want to keep named references to things you could use an object.
var playerNames = {};
playerNames['p1'] = document.getElementById("id_1playerName").value;
playerNames['p2'] = document.getElementById("id_2playerName").value;
for (i = 1; i <= 2; i++) {
// dynamically get access to each value
alert.log(playerNames['p' + i])
}
I want to create a mutable reverse method for a javascript string.
TL; DR:
Here is my attempt that did not work:
String.prototype.reverse = function() {
var reversed = {};
j = 0;
for (i = this.length - 1; i >= 0; i--)
{
reversed[j++] = this[i];
}
for (i in reversed)
{
this[i] = reversed[i];
}
};
...
str1 = "hello";
str1.reverse();
console.log(str1); //hello, not olleh
It doesn't change the string at all, as further evidenced by this small test:
String.prototype.makeFirstCharX = function() {
console.log(this[0]); //h
this[0] = 'x'; //no error
console.log(this[0]); //h ??
};
str1.makeFirstCharX();
console.log(str1); //hello, not xello
Is there anyway to overwrite values of this in a new protoype function for a native JS type? Why doesn't something like this[0]='x' give an error instead of just silently failing?
---This is what I tried on a custom JS object that did work as expected, which is what I based the above off of:
I can create a custom revsersible string that behaves similarly to a native string like this:
function MyString(str) {
//set string content and length
var l = 0;
for (i in str)
{
this[i] = str[i];
l++;
}
this.length = l;
}
MyString.prototype.toString = function()
{
var retVal = '';
for (i = 0; i < this.length; i++)
{
retVal += this[i];
}
return retVal;
};
MyString.prototype.reverse = function()
{
var reversed = {};
j = 0;
for (i = this.length - 1; i >= 0; i--)
{
reversed[j++] = this[i];
}
for (i in reversed)
{
this[i] = reversed[i];
}
};
So as expected:
str = new MyString('string');
console.log(str); // MyString { 0="s", 1="t", 2="r", more...}
console.log("" + str); //string
console.log(str.length); //6
str.reverse();
console.log(str); // MyString { 0="g", 1="n", 2="i", more...}
console.log("" + str); //gnirts
But if I try the same thing on a "real" javascript string, it does not work.
First Strings aren't mutable in Javascript.
from the rhino book:
In JavaScript, strings are immutable objects, which means that the
characters within them may not be changed and that any operations on
strings actually create new strings. Strings are assigned by
reference, not by value. In general, when an object is assigned by
reference, a change made to the object through one reference will be
visible through all other references to the object. Because strings
cannot be changed, however, you can have multiple references to a
string object and not worry that the string value will change without
your knowing it
Also Javascript passes it by value. Which means that you aren't modifying your original string anywhere. You have to return something.
Here's a simple implementation for the reverse function:
function reverse(s) {
var reversed = '';
for (var i = s.length - 1; i >= 0; i--)
reversed += s[i];
return reversed;
}
You have to reassign the original var.
var original = 'original';
original = reverse(original);
The bracket notation isn't going to work. From String:
For character access using bracket notation, attempting to delete or
assign a value to these properties will not succeed. The properties
involved are neither writable nor configurable. (See
Object.defineProperty for more information.)
Strings are immutable in Javascript so you're not going to be able to change them by any means.
I need to create javascript objects that base on user defined number. So if user defines 20, then I need to create 20 variables.
var interval_1=0, interval_2=0, interval_3=0, interval_4=0, interval_5=0... interval_20=0;
how do I do it so the name of the object can be dynamically created?
for (i=0; i<=interval; i++){
var interval_ + i.toString() = i;
}
Erm, use an array?
for( i=0; i<=count; i++) array[i] = i;
Use an array:
var i, count, interval = [];
// user defines count, 20 for example
count = 20;
for (i = 0; i < count; i++) {
interval.push(i);
}
// interval[0] === 0
// interval[19] === 19
// interval.length === 20
Note, this starts the index at 0 and goes up to count - 1. Do not use i <= count unless you start i at 1.
Here is a jsFiddle to illustrate. Hit F12 to open dev tools in most browsers and look at console, or change console.log() to alert().
Link: http://jsfiddle.net/willslab/CapBN/1/
Alternatively, you could setup a single object with properties for each value:
var i, count, intervals = {};
count = 20;
for (i = 0; i < count; i++) {
intervals["interval_" + i] = i;
}
//intervals.interval_0 === 0
//intervals.interval_19 === 19)
Link: http://jsfiddle.net/willslab/EBjx7/2/
for (i=0; i<=20; i++){
window["interval_" + i.toString()] = i;
}
Javascript variables can be created by:
a variable declaration, e.g. var x;
assigning a value to an undeclared variable, e.g. y = 'foo';
an identifier in a formal parameter list, e.g. function bar(x, y, z);
using eval, e.g. eval( 'var x = 4');
If all else fails and you want say 5 variables, you can do:
var s = [];
var i = 5;
while (i--) {
s[i] = 'a' + i;
}
eval('var ' + s.join(',') + ';');
alert(a0); // shows undefined
If a0 wasn't defined, the last step would throw a reference error.
Of course the issue you now have is how to access them. If they are created as global variables, you can use:
globalObj['a' + i];
where globalObj is usually window, however there is no equivalent for accessing function variables since you can't access their variable object.
So the usual solution is to put things into arrays or objects where you can iterate over the properties to find things you don't know the name of.