Convert string value into variable value - JavaScript - javascript

I have a string variable: id = '1';
I want to make a variable that holds the value of data.img + id + .dispWidth without making it a string.
For example, if id = '7'; then dw = data.img7.dispWidth;
How can I do this?

Use bracket notation to use dynamic property keys
dw = data['img' + id].dispWidth;

data['img' + id].dispWidth should do it. Although at that point you should probably consider whether you don't actually want an array.

Related

Dynamic property name concatenation

I'm looking for an easy way to assign to a variable depending on the value of another variable.
device.slot2_clipList[clipNumber] = singleClipDetails;
what I'm trying to do is: replace the "2" with another variable, so that i can run the same operation while just changing the
var slotNumber, and write to the corresponding variable.
i tried
device.slot + device.slotNumber + _clipList[clipNumber]
but (obviously?), this doesn't work.
How can this be done? (Maybe I named the Question incorrectly, but that was the closest I could think of.)
Thanks
This is what bracket notation is for
var i = 2;
device['slot' + i + '_clipList'][clipNumber] = singleClipDetails;
device['slotNumber' + _clipList[clipNumber] ]
Explanation:
foo.bar in javascript is identical (even in performance) to foo['bar']. So any object property name can be built up from strings.

creating variable names from parameters in javascript

I was wondering if it is possible to create variable names from parameters passed to a function in javascript. Something like this:
function createVar(number) {
var "number" + number;
}
createVar(1)
I'm new to Stack Overflow and programming, so any help would be appreciated.
You could attach this to the window object, but note it will be global. For example:
function createVar(varName, value) {
window[varName] = value;
}
createVar("test", "Hello World");
alert(test); // Outputs "Hello World".
It is possible to interpret Object as associative array where you specify index and get value by name of index ( hash ):
var x = Array();
x[number] = value;
Single variable name is for programmer, and the code would be hard to maintain and understand when you set variable dynamically in code.
Honestly, I don't see why this would ever be useful, because every time you want to use the variable you'd have to search for it with your number argument.
However, you can do it, albeit not the exact way you had described:
function createVar(number){
eval("var number" + number.toString() + ";");
}
however, this variable will only be accessible within the function, to make it global assign to the window object:
function createVar(number){
window["number" + number] = 15; // creates "global" variable
}
As I've stated before, however, I don't see this being useful, [i]ever[/i], if you want to stratify values by numbers you'd be much better off with an array.

Jquery new Element Resulting in [object object] when concatenated

I am trying create a new Anchor tag in Jquery with some attribute and storing it in variable, but when i concatenate it with other variable and append to Dom it gives [OBJECT OBJECT]
JsFiddle for the Same :
http://jsfiddle.net/T8q6T/
var a_name = "Sathwick Rao (sgmdev#gmail.com)^$^4083372345";
var _name = a_name.split('(')[0];
var _part1 = a_name.split('(')[1];
var _email = _part1.split(')')[0];
var htmlElement = $('<a>('+_email+')</a>').attr('href','mailto:'+_email);
$('#shara').html(_name+' '+htmlElement);
You can't concatenate a string with an object like that. Separate the two statements like this:
http://jsfiddle.net/E2Rur/
$('#shara').html(_name).append(htmlElement);
It's because you are trying to concatenate an object with a string. Therefore, the object gets implicitly converted to it's string representation by it's toString function.
E.g.
var div = document.createElement('div');
'some string' + div.toString(); //"some string[object HTMLDivElement]"
'some string' + div; //"some string[object HTMLDivElement]"
If you want to concatenate the outerHTML of the element with some other HTML string that is possible however.
$('#shara').html(_name + ' ' + htmlElement.prop('outerHTML'));
However it's not necessary the most optimal or clean way when it's not necessary.
$('#shara').append($('<span>').addClass('name').text(_name).add(htmlElement));
As you may have noticed, I add the htmlElement to the set and perform a single append operation rather than chaining two append calls. That's to avoid multiple DOM reflows, which are quite expensive.
If you do not want the wrapping span and use the same solution, you can also do:
$('#shara').append($(document.createTextNode(_name + ' ')).add(htmlElement));
To force the variable htmlElement to store a string, I sometimes hack it like this
var htmlElement = $('<a>('+_email+')</a>').attr('href','mailto:'+_email)+"";
$('#shara').html(_name+' '+htmlElement);

javascript variable always undefined

When I want to redirect, the variable where is always udefined. But, for example, I want put that variable in alert(); it shows correct number.
code
var where = msg.txt;
window.location = "/page.php?id=".where; //this redirects to /page.php?id=undefined
alert(where); //it show correct number
It should be:
window.location = "/page.php?id=" + where;
You have:
"/page.php?id=".where;
Which tries to retrieve a where property of a string, and such has not been defined.
In JavaScript, . is used for property access, not for string concatenation like in PHP.
Use + instead:
window.location = "/page.php?id=" + where;

Dynamic Javascript - Is This Valid?

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.

Categories