Access variables like a text? - javascript

Let's say i got a variable Var123;
var x = "Var";
var VariableMixLOL = x + "123";
//so VariableMixLOL should be equal to Var123, ex. Var123 = "Abc", VariableMixLOL should be "Abc" too
How can I do this? Btw i'm using as3
PS: Added at Tags JS too because i think it's the same thing

One option is to use eval()
var x = "Var";
var Var123 = "lalaala";
var VariableMixLOL = eval( x + "123" );
Another option and the better one is to model such things in a JavascriptObject.
var x = "variable";
var variables = { "variable123" : "laalala"}; //OR variables = {}; variables["variable123"] = "laalala";
var VariableMixLOL = variables[ x + "123"];

Variable name as String can be used if you incorporate an object to which you store it.
For example:
var x = "Var";
var compoundVar = x + "123";
var obj : Object = {};
obj[compoundVar] = 7;
//Now you can call the variable like this
trace(obj.Var123); //7

Related

String to number conversion using JavaScript

This is my html code but the problem is that if I add two strings it always gives the 50 as the addition.
function add()
{
var fname=document.getElementById("fname");
var lname = document.getElementById("lname");
var fstring = fname.toString();
var lstring = lname.toString();
var fl = fstring.length;
var ll = lstring.length;
var f1 = parseInt(fl,10);
var l1 = parseInt(ll,10);
document.getElementById("result").innerHTML = f1 + l1;
}
</script>
Because you are NOT reading the value of the input
var fname=document.getElementById("fname");
var lname = document.getElementById("lname");
var fstring = fname.toString(); //<-- turning object to string
var lstring = lname.toString(); //<-- turning object to string
needs to be
var fname=document.getElementById("fname");
var lname = document.getElementById("lname");
var fstring = fname.value;
var lstring = lname.value;
I think the issue is that you are getting the Element itself, rather than the content of the given element. For example if fname was an input, you'd want to call
var fname=document.getElementById("fname").value;
Current what I'm guessing is happening is that calling toString() on the element itself returns something like [object HTMLInputElement], hence why you always get the same lengths when you do the addition.
If you get the values rather than the elements, your code should then work as expected.
var fstring = fname.toString();
var lstring = lname.toString();
This tries to convert the HTMLElement objects to string, while what you probably want is the value stored in those inputs.
var fstring = fname.value;
var lstring = lname.value;
Also, you don't need to do this:
var fl = fstring.length;
var ll = lstring.length;
var f1 = parseInt(fl,10);
var l1 = parseInt(ll,10);
The length property is a number already.
If you wanted to get the total length of both names, just do
total = fstring.length + lstring.length;
If you wanted to concatenate them, do
fullname = fstring + " " + lstring;
And finally, don't put 1's and small L's in short variable names like that, this can become quite confusing.
Use This
function add(){
var fname=document.getElementById("fname");
var lname = document.getElementById("lname");
var fstring = fname.value.toString();
var lstring = lname.value.toString();
var fullName = fstring +" "+lstring;
alert(fullName )
}
<input type='text' id='fname'/>
<input type='text' id='lname'/>
<input type='button' id='btnOk' onclick='add()' value='OK'/>

How to combine variables of 2 events into one as sum of both. jquery

Basically I'm trying to create simple price calculator. There are 2 functions which calculates price on select event. How I can sum values of these 2 functions into one, and then add it to ".sum" div ?
var xx = j('select[name="miestas"]').change(function(){
var kainos = {"vln":"55", "kns":"150"};
var val = j(this).find(":selected").text();
kaina1 = kainos[val];
return kaina1;
});
var zz = j('select[name="vardas"]').change(function(){
var kainos = {"vln":"35", "kns":"30"};
var val = j(this).find(":selected").text();
kaina2 = kainos[val];
return kaina2;
});
j('select').change(function(){
j('.sum').html(zz + xx); });
Don't return anything from those functions, assign the result to some global variables:
var xx;
var zz;
and inside the handlers:
...
xx = Number(kaina1);
...
zz = Number(kaina2);
Working example:
http://jsfiddle.net/txkmD/1/

How can I concatenation parameter name out of 2 strings? [duplicate]

This question already has answers here:
How to use a string as a variable name in Javascript? [duplicate]
(3 answers)
Closed 9 years ago.
I have the following variable:
var MyVar = "8";
I have 2 strings for example:
var foo = "My";
var bar = "Var";
Now I want to alert MyVar value, meaning to alert "8" and not "MyVar"
alert(foo + bar) // returns "MyVar"
This is a rare case where eval will be needed:
Code
var MyVar = "8",
foo = "My",
bar = "Var";
alert(eval(foo + bar))
Link: http://jsfiddle.net/howderek/wcVNU/
Assuming it's a global variable:
alert(window[foo + bar])
But you're probably better off using objects and properties for that. Object properties can also be accessed with bracket notation:
var obj = {
MyProp : 8
};
var foo = "My";
var bar = "Prop";
alert(obj[foo + bar]);
Without changing the context to much of what you are doing you can use the eval function. However, you have to be very careful with it.
var MyVar = 8;
var foo = "My";
var bar = "Var";
alert(eval(foo + bar));
Depending on what your doing though there are a lot of ways to do this. If you assign MyVar to be part of some context such as this, or window you can simply lookup the value with the key as the variable name.
Window Context
(function () {
window.MyVar = 8;
var foo = "My";
var bar = "Var";
alert(window[foo+bar]);
})();
Function Context
new (function () {
this.MyVar = 8;
var foo = "My";
var bar = "Var";
alert(this[foo+bar]);
})();
Object Context
(function () {
var obj = {}
obj.MyVar = 8;
var foo = "My";
var bar = "Var";
alert(obj[foo+bar]);
})();

javascript re-define a variable

I'm getting stuck somewhere (as newbies do). Is it ok to re-define a variable once it has been trimmed and tested for content?
function setarea() {
var dbasedata = document.forms[0]._dbase_name.value;
dbasedata = dbasedata.toUpperCase();
dbasedata = dbasedata.replace(/\s/g, "");
dbasedata = dbasedata.remove("UK_CONTACTS", "");
if (dbasedata != "") {
_area.value = _dbase_name.value;
}
else var dbasedata = document.forms[0]._dbase_name.value;
dbasedata = dbasedata.toUpperCase();
dbasedata = dbasedata.replace(/\s/g, "");
if (dbasedata.indexOf("UK_CONTACTS")>-1 {
var dbaseterm = "UK_CONTACTS";
else var dbaseterm = "";
}
It makes no sense to use var more than once for the same variable in the same scope. Since all var x; are hoisted to the top of the scope every additional var on that variable will be a no-op.
Assigning a new value is fine though - they are variables and not constants after all.
function x() {
var x = 123;
foo();
x = 456;
var y = 'hello';
var x = 678;
}
is actually this internally:
function x() {
var x, y; // both are === undefined
x = 123;
foo();
x = 456;
y = 'hello';
x = 678;
}
Yes, you can do this and it is legal.
It may 'work', but isn't recommended. You don't need to redeclare it.
Probably want to run your code through JSLint . There are a few tidyness/bracing issues you would want to address.

Javascript property: Built out of strings

I need to built a object property out of strings
but how could I use the value of this string as property name?
var x = 'a';
var y = 'b';
var xy = x + y;
var z = {
xy: 'some text'
};
Now I could access it via z['xy'] but not via z['ab'].
You're trying to write
var z = {};
z[xy] = 'some text';
You cannot do this using an object literal.
As #SLaks has said here - its not possible with object literals ... you could use an array though :
var x = 'a';
var y = 'b';
var xy = x + y;
var z = []; // define array
z[xy]='some text';​​​
alert(z['ab']); // outputs 'some text'
​

Categories

Resources