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.
Related
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 do something like:
var arr = []
for var(i=0;i<x;i++){
arr.push{ get num(){return this.previousArrayElement.num + randomNumber}}
}
how can I treat "previousArrayElement"?
I think you are just trying to create an array of size x containing numbers in order of size and separated by randomNumber intervals? Something like this would work:
var x = 100;
var arr = [0]
for (i=1; i<x; i++) {
arr.push( arr[i-1] + Math.random() );
}
Note that by starting the array out with an initial value (index 0) and beginning your iteration with the second value (index 1) you don't have to worry about accessing the 0-1 element at the first iteration.
I hope that helps!
Not 100% sure this is what you want. Expected output shown is not valid syntax and details provided are very open to interpretation
var arr = []
for (var i=0; i < x; i++){
var num = i > 0 ? arr[i-1].num : 0;
num= num + randomNumber; // is this an existing variable?
arr.push({ num: num}); // used object with property `num` based on example `previousArrayElement.num `
}
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.
So why myarray[bla][bl] always equal to NaN? If I do the same thing with 1 dimension (myarray[bla]), I get the number.
var bla = 'blabla';
var bl = 'bla';
var myarray = [];
for (i = 0; i < 10; i++) {
if (!myarray[bla]) {
myarray[bla] = [];
}
myarray[bla][bl] += i;
console.log(myarray[bla][bl] + " + " + i);
}
Ok, so let's step through your loop, replacing instances of the variable bla with the string value of 'blabla':
if (!myarray['blabla']) {
myarray['blabla'] = [];
}
Arrays in javascript are index by integer values. What your code here is doing is adding an expando property to the array instance named blabla. That is:
myarray.blabla = [];
now reconsider your increment statement:
myarray['blabla'][bl] += i;
or, with the expando properties:
myarray.blabla.bl // remember that "myarray.blabla" is set to the empty array above
What this is trying to do is access the property named bl on the empty array. That's why you're getting undefined here.
Anyway, as a best practice, you might want to avoid using arrays in javascript like hashtables, since problems like this are bound to crop up after enough time.
If we expand a little I hope you can see the problem,
if (!myarray[bla]) {
myarray[bla] = [];
}
myarray[bla][bl] = myarray[bla][bl] + i;
Hint: myarray[bla][bl] = undefined
because myarray[bla][bl] is not set... , you need
if ( !myarray[bla][bl] ){ myarray[bla][bl] = 0; }
I am looking to do something very similar to the following PHP code but in javascipt:
for ($weenumber = 1; $weenumber <= 30; $weenumber++)
{
$weenumber = str_pad($weenumber, 2, "0", STR_PAD_LEFT);
echo $_POST["entry{$weenumber}_cash"];
}
Basically accessing the loop number padded with a trailing 0 if less than 10 but I dont know the syntax in JS to do this :(
Sorry for noob style question
I think that you mean a leading zero rather than a trailing zero...
You can for example use the conditional operator:
(n < 10 ? '0' : '') + n
You could also implement a general purpose function:
function padLeft(str, len, ch) {
while (str.length < len) str = ch + str;
return str;
}
To access an object property by name in Javascript you use brackets. Example:
var value = obj['entry' + (n < 10 ? '0' : '') + n + '_cash'];
If n contains 4, this will be the same as obj.entry04_cash.
Whether or not there's a specific function to do this, if you know how to use an if clause, and you know how to perform string concatentation (using the + operator if you didn't), then you should be able to easily roll you own version of str_pad by hand (which works for numbers below 100).
Think about the cases involved (there are only two) and what you need to output in either case.
This is the code you should use:
for(var i=0; i<30; i++){
document.writeln(i<10 ? "0"+i : i);
}
change document.writeln() with any function you want to handle the data
for (weenumber = 1; weenumber <= 30; weenumber++) {
weenumber = str_pad(weenumber, 2, "0", STR_PAD_LEFT);
}
For the str_pad() function, you can use PHPJS library:
http://phpjs.org/functions/str_pad:525
This library will also ease transition from php to javascript for you. Check it out.
for(var i=0; i<30; i++)
{
var index = i;
if(i<10) index = "0" + index
var elem = document.getElementById("entry"+index);
}
var someArray = [/*...*/];
for (var i= 1;i<= 30;i++)
{
var weenumber = i+"";
for(var j=weenumber.length;j<2;j++)
weenumber = "0" + weenumber;
var key = "entry" + weenumber + "_cash";
document.write(someArray[key]);
}
Here's a function you can use for zeropadding:
function zeroPad(nr,base){
var len = (String(base).length - String(nr).length)+1;
return len > 0? new Array(len).join('0')+nr : nr;
}
//usage
alert(zeroPad(3,10)); //=> 03
or extend the Number prototype
Number.prototype.zeroPad = Number.prototype.zeroPad ||
function(base){
var nr = this, len = (String(base).length - String(nr).length)+1;
return len > 0? new Array(len).join('0')+nr : nr;
};
//usage
var num = 1;
alert(num.zeroPad(100)); //=> 001
Now for the variable name part: if it's a global variable (not advisable) that variable is a property of the global object, in a browser that's window. You can get a variable by its dynamic name using the equivalent of: window['myvariable'+myJustResolvedNumericValue]. Within an object (instance) you can use the same bracket notation: myObject['myvariable'+myJustResolvedNumericValue].
Using this information, in javascript your function could look like:
for (var weenumber = 1; weenumber <= 30; weenumber++)
{
// execute something using the variable that uses the counter in the
// variable name as parameter
executeSomeFunction(window['entry'+weenumber.padLeft(10) + '_cash']);
}