Say I have to following code:
var numb = $(selector).length;
And now I want to dynamicly make variables based on this:
var temp+numb = ...
How would I be able to do this?
Edit:
I know some of you will tell me to use an array. Normally I would agree but in my case the var is already an array and I rly see no other solution than creating dynamic names.
Variables in Javascript are bound to objects. Objects accept both . and [] notation. So you could do:
var num = 3;
window["foo"+num] = "foobar";
console.log(foo3);
PS - Just because you can do that doesn't mean you should, though.
In global scope (not recommended):
window["temp"+numb]='somevalue;
window.console && console.log(temp3);
In a scope you create - also works serverside where there is no window scope
var myScope={};
myScope["temp"+numb]="someValue";
window.console && console.log(myScope.temp3);
Related
So I'm copying a $scope.property by defining it as the value of another variable var query, and when I update the value of var query it changes the value of $scope.property.
Why does this happen and how can I avoid this?
My code looks something like this:
var query = $scope.property;
if(condition) {
console.log($scope.property);
$.extend(query, anotherObj);
console.log($scope.property);
}
The output in the console looks like this:
> Object {details-type: "order", details-bind_date_formatted: "03/19/2013"}
> Object {details-type: "order", details-bind_date_formatted: "03/19/2013", details-state: "CA"}
I've never encountered this problem in vanilla javascript.
Why does this happen
You noticed that query === $scope.property? The both refer to the exact same object, which you alter between the two log statements.
and how can I avoid this?
How do you want to avoid this? Do you expect query to be a clone of the object? Then see How do I correctly clone a JavaScript object? or What is the most efficient way to deep clone an object in JavaScript? for that.
I've never encountered this problem in vanilla javascript.
Unlikely, since jQuery is only built of vanilla JS:
var scope = {a:{b:1}};
var a = scope.a;
console.log(scope.a); // or just log(a);
a.c = 0; // or scope.a.c = 0;
console.log(scope.a); // or just log(a);
var query = angular.copy($scope.property);
On (document).ready im would like to dynamically generate elements inside a certain parent-element. Lets call them "Candles".
Each "Candle" needs different properties for backgroundImage and color depending on their index().
After creating the page, these attributes need to be changeable via the interface. So its important to save the properties of the "candles" independent from each other.
Thats why I thought it might be useful, to generate for an object for each "Candle" to save their individual properties and to make them editable.
var candleAmount = 3;
for (var i=1; i <= candleAmount; i++) {
$("#container #candles").append("<li><img src=''></img></li>");
var Candle+i = [ "background":"+i+", "color":" - random - (ignore)" ]
};
(please dont mind any failures in the code besides the "Candle+i", I'll figure it out.)
EDIT: Ok, thank you so far. I might not made myself clear enaugh.
Here is an way more reduced example:
$("ul#candles li").each( function(i) {
candle+i = i+" Anything";
});
alert(candle4);
I would love to create an amount of variables depending on the Amount of child-objects.
What would be the correct syntax, or isn't there any?
Thank you
just put them in an array and access them via index. Result is most likely the same for you and is much better than let them floating in your scope
So is there any way, to generate object-names with an index?
Yes, in JavaScript, global variables are defined as properties of the global-object. (Inside a function, variables are defined as properties of the Activation object.) You can reference the global object by window (for browser applications) or just by this.
And because all objects are associative you can give there properties just the name you want. So, setting a global variable is equal to set a property into the global object.
var foo = "bar"; === this["foo"] = "bar";
Now, its just a small step to add a dynamic part to the name:
for(var i=0;i<10;i++) {
this['candle' + i] = i;
}
alert(candle7);
For your specific code:
$("ul#candles li").each( function(i) {
window["candle" + i] = i+" Anything";
});
alert(candle4);
I had the following question in a test today. But i had not see something like functionName.VariableName before. Not sure how that works.
Would be great if you can tell me the solution:
function Item(itemName)
{
var next_item_id = 1;
Item.item_name = itemName;
Item.item_id = next_item_id++;
}
var Item1 = Item('Desktop');
var Item2 = Item('Laptop');
var Item3 = Item('Monitor');
Anything wrong with the code above? if yes fix it. (The problem i would see is next_item_id is always 1, need to make it global?)
Modify the function so that the variable “next_item_id”, cannot be modified during run time.
My own question, how does the variable like Item.item_name work? I want to google it, but not sure what I should search for.
Thanks.
Your thinking is close in that next_item_id will always be 1, but it's generally not recommended to pollute the global namespace. Instead, wrap it in an anonymous function:
(function() {
var next_item_id = 1;
function Item(itemName)
{
//Use "this" to apply the property to the instance only
this.item_name = itemName;
this.item_id = next_item_id++;
}
var Item1 = new Item('Desktop');
var Item2 = new Item('Laptop');
var Item3 = new Item('Monitor');
})()
Also, as in Java, the general best practice in Javascript is to use camelCase rather than under_scores. Constructors are generally in UpperCamelCase. Examples:
Array //UpperCamelCase
Object.prototype.toString //toString is camelCase
This question is ambiguous, and, depending on the interpretation, there can be a number of possible answers. next_item_id is a "var" declared inside a function and naturally has an internal [[DontDelete]] and [[DontEnum]] flag. If it's a "var" and we're not using "this" as shown in my modified code, the variable is inherently not accessible outside of the function or its nested functions and therefore cannot be modified. You can use the non-standard const or you can create an object and use Object.defineProperty to create a setter that returns false assuming an ES5-compatible environment, etc.
Functions are objects in Javascript. All objects can have "properties."
Javascript functions are also objects and can have properties.
They behave like static fields in Java.
You're going about it all wrong. I'm assuming that you want to set internal variables.
If you want to create a 'constructor', do something like this:
function Item(itemName)
{
var next_item_id = 1;
this.item_name = itemName;
this.item_id = next_item_id++;
}
var Item1 = new Item('Desktop');
var Item2 = new Item('Laptop');
var Item3 = new Item('Monitor');
Both item_name and item_id will be publicly available. To make use next_item_id like you want, try this:
Item.next_item_id = 1;
Then in your constructor, do Item.next_item_id++;
Your final code should look something like this:
function Item(itemName)
{
this.item_name = itemName;
this.item_id = Item.next_item_id++;
}
Item.next_item_id = 1;
var Item1 = new Item('Desktop');
var Item2 = new Item('Laptop');
var Item3 = new Item('Monitor');
What this is doing is attaching a property to the object Item. You might be thinking, "Item is a function! How is this possible?!". Nearly everything in JavaScript is an object with mutable properties. The only things that aren't are the keywords null and undefined (AFAIK).
Item is still a function, but it also has a property next_item_id.
Also, using new will create a new instance. This is a similar concept as in Java and other programming languages. Just calling Item is like calling a function, and you'll get back whatever is returned from it (through an explicit return statement, otherwise undefined).
Answer for question 2 : Modify the function so that the variable “next_item_id”, cannot be modified during run time.
If I have interpreted your question correctly, you want to have Item.item_id as a constant that cannot be modified any where outside the constructor. I don't think we can have constants in JS.
Item1.item_id = someValue
Above line, used some where can change the item_id value of Item1.
can someone tell me if this is valid javascript? I know you couldnt do this sort of thing in c# but js is a much looser language..
var arrayToUse = "arr" + sender.value;
for (i = 0; i <= arrayToUse.length; i++) {
// something..
}
specifically - the dynamic generation of the array name..
update..
so i have an array called arrMyArray which is initialised on document ready. sender.value = "MyArray" - but could be something else eg MyArray2
I want to dyanimcally iterate over the array that is indicated by the sender.value value.
Yes, this is entirely valid.
arrayToUse will be a string (regardless of the value of sender.value — it will be converted to a string), and i will iterate from 0 to the string's length).
One minor note: it should be for (**var** i = 0; …), otherwise i will be treated as a global variable, which will almost certainly end badly if you've got multiple loops running at the same time.
Edit: you want to get the array based on the name? In that case you've got to look it up in whatever context the array is defined.
If it's a global array, use window.
For example:
var arrayName = "arr" + sender.value;
var array = window[arrayName];
…
To get a variable name defined by a variable, you need to use eval, like so:
var arrayToUse = eval("arr" + sender.value);
However, you must be very careful with this, because controlling sender.value would allow someone to hijack your entire application this way. You should usually try to find another solution.
If the variable is defined at the globally, you can look it up as window["arr" + sender.value] instead. This is still not ideal, but is less of a security risk.
What you need to do is access a variable with the name "arr" + sender.value. Accessing the variable whose contents are "arr + sender.value doesn't do what you want -- that's just a string.
To access the variable with that name, you can look it up as a global (globals are members of the window object in the browser):
window["arr" + sender.value]
This is safer and faster than using eval() because it doesn't run code in a JavaScript execution context to evaluate the string -- it just looks up a variable in the window object with that name.
Is there is any way/tool to detect the duplicated variables/methods names in the project JavaScript files?
There is no such thing as duplicate names in Javascript. You will never get an error when re-declaring a name that already exists.
To avoid overwriting existing names in Javascript, good developers do at least one of these things:
1) Carefully keep their variables out of the global scope, usually adding all names needed for the app under just one or two globally-scoped objects.
// No
var foo = 1;
var bar = 2;
var bas = 3;
// Yes
var MyApp = {
foo:1,
bar:2,
bas:3
}
2) Check that a variable name does not yet exist before creating it.
// No
var MyObj = {};
// Yes
var MyObj = MyObj || {} // Use MyObj if it exists, else default to empty object.
jsLint might help you
http://www.jslint.com/
JavaScript Lint can probably help:
http://javascriptlint.com/
http://javascriptlint.com/