Javascript property: Built out of strings - javascript

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'
​

Related

What's the best way to allocate the variables with multiple combinations

I want to reduce the initialization of multiple combination variables.
My aim is to create a function and pass a function with variable.
If I pass a variable x into function value(x); I should get output as "123". Similarly, if I pass a variable xy into function value(xy), then I should get output as "123456". Basically, I want to concatenate variables
Here is the javascript code as
var x = "123";
var y = "456";
var z = "789";
var a = "0-+";
var xy = x + y;
var yz = y + z;
var zx = z + x;
var xa = x + a;
var ya = y + a;
var za = z + a;
var ax = a + x;
var ay = a + y;
var az = a + z;
var xz = x + z;
var yx = y + x;
var zx = z + x;
var zy = z + y;
var xyz = x + y + z;
var xyza = x + y + z + a;
function value(input) {
console.log(input);
}
Sample execution as follows:
value(x); //output: 123
value(y); //output: 456
value(xy); //output: 123456
value(za); //output: 7890-+
In this case, there are lots of combination for the above variables i have defined to meet all possible combinations. I want to validate the user input from the above combination and also i dont want to write so many variables. Is there any possible easy solution ?
Please suggest. Thanks
I would declare a global object to store the variables as keys:
var globals = {
"x": "123",
"y": "456",
"z": "789"
};
Note that you can refer to your "variables" by globals.x, or globals.y (you can replace globals with a shorter keywork to reduce code of course).
It is a little extra effort to define the "variable names" with quotes.
However, now you get to use:
alert(Combinate("xz"));
// output: 123789
With a function like:
function Combinate(phrase) {
result = "";
for (var i = 0, len = phrase.length; i < len; i++) {
result += globals[phrase[i]];
}
return result;
}
Here's a JSFiddle.
You'll want to use some form of iterating over an array or object. As an example:
var x = "dave";
var y = "bill";
var z = "john";
var a = "suzan";
var people = [x,y,z,a];
for(i=0; i<people.length; i++) {
for(x=0; x<people.length; x++) {
value(people[i] + people[x]);
for(y=0; y<people.length; y++) {
value(people[i] + people[x] + people[y]);
for(z=0; z<people.length; z++) {
value(people[i] + people[x] + people[y] + people[z]);
}
}
}
}
// not sure why you'd have a function to wrap console.log(), but...
function value(input) {
console.log(input);
}
See in action on jsFiddle.
There are more elegant paths, but this should get you on the road to learning about JavaScript.

Access variables like a text?

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

var x, y = 'foo'; Can this be accomplished?

Since it is possible to do:
var x = 'foo', y = 'foo';
Would this also be possible?
var x, y = 'foo';
I tried it, however x becomes undefined.
I know this may seem like a silly or redundant question, but if I'm curious about something, why not ask? Also you will probably wonder why I would need two variables equal to the same thing in scope. That is not the point of the question. I'm just curious.
Not sure if this is what you're asking, but if you mean "Can I assign two variables to the same literal in one line without typing the literal twice?" then the answer is yes:
var x = 10, y = x;
You need two separate statements to get the exact same semantics.
var x, y; x = y = 'foo';
// or
var x = 'foo'; var y = x;
// or
var y; var x = y = 'foo';
The solution other users are suggesting is not equivalent as it does not apply the var to y. If there is a global variable y then it will be overwritten.
// Overwrites global y
var x = y = 'foo';
It is a good practice to correctly apply var to local variables and not omit it for the sake of brevity.
You can do
var x = y = 'test'; // Edit: No, don't do this
EDIT
I just realized that this creates/overwrites y as a global variable, since y isn't immediately preceded by the var keyword. So basically, if it's in a function, you'd be saying "local variable x equals global variable y equals …". So you'll either pollute the global scope, or assign a new value to an existing global y variable. Not good.
Unfortunately, you can't do
var x = var y = 'test'; // Syntax error
So, instead, if you don't want to pollute the global scope (and you don't!), you can do
var x, y;
x = y = 'test';
In order for that to work, you will either need to initialize them separately (like your first example) or you will need to set them in a separate statement.
// This causes bugs:
var x = y = 'test';
Watch:
var y = 3;
function doSomething(){ var x = y = 'test'; }
doSomething();
console.log( y ); // test !?
On the other hand:
// this does not
var x,y; x = y = 'test';
Watch:
var y = 3;
function doSomething(){ var x,y; x = y = 'test'; }
doSomething();
console.log( y ); // 3 -- all is right with the world.
Below is my test function. The currently uncommented line in the pollute function does what you were looking for. You can try it and the other options in jsfiddle here.
var originalXValue = 'ekis';
var originalYValue = 'igriega';
var x = 'ekis';
var y = 'igriega';
function pollute()
{
// Uncomment one of the following lines to see any pollution.
// x = 'ex'; y = 'why'; // both polluted
// var x = 'ex'; y = 'why'; // y was polluted
// var x = y = 'shared-ex'; // y was polluted
var x = 'oneline', y = x; // No pollution
// var x = 'ex', y = 'ex'; // No pollution
document.write('Pollution function running with variables<br/>' +
'x: ' + x + '<br/>y: ' + y + '<br/><br/>');
}
pollute();
if (x !== originalXValue && y !== originalYValue)
{
document.write('both polluted');
}
else if (x !== originalXValue)
{
document.write('x was polluted');
}
else if (y !== originalYValue)
{
document.write('y was polluted');
}
else
{
document.write('No pollution');
}
Note that although
var x = y = 'test';
is legal javascript
In a strict context (such as this example):
function asdf() {
'use strict';
var x = y = 5;
return x * y;
}
asdf();
You will get:
ReferenceError: assignment to undeclared variable y
to have it work without error you'd need
var x, y;
x = y = 5;
You'd use var x, y = 'foo' when you want to explicitly initialize x to undefined and want to restrict the scope of x.
function foo() {
var x, y = 'value';
// ...
x = 5;
// ...
}
// Neither x nor y is visible here.
On the other hand, if you said:
function foo() {
var y = 'value';
// ...
x = 5;
// ...
}
// y is not visible here, but x is.
Hope this helps.
Source: http://www.mredkj.com/tutorials/reference_js_intro_ex.html
I would avoid being tricky. Since I only use one variable per var (and one statement per line) it's really easy to keep it simple:
var x = "hello"
var y = x
Nice, simple and no silly issues -- as discussed in the other answers and comments.
Happy coding.
I am wondering why nobody posted that yet, but you can do this
var x, y = (x = 'foo');
You can't do
var a = b = "abc";
because in that case, b will become a global variable.
You must be aware that declaring a variable without var makes it global. So, its good if you follow one by one
var a = "abc";
var b = a;

How do I combine 2 javascript variables into a string

I would like to join a js variable together with another to create another variable name... so it would be look like;
for (i=1;i<=2;i++){
var marker = new google.maps.Marker({
position:"myLatlng"+i,
map: map,
title:"title"+i,
icon: "image"+i
});
}
and later on I have
myLatlng1=xxxxx;
myLatlng2=xxxxx;
Use the concatenation operator +, and the fact that numeric types will convert automatically into strings:
var a = 1;
var b = "bob";
var c = b + a;
ES6 introduce template strings for concatenation. Template Strings use back-ticks (``) rather than the single or double quotes we're used to with regular strings. A template string could thus be written as follows:
// Simple string substitution
let name = "Brendan";
console.log(`Yo, ${name}!`);
// => "Yo, Brendan!"
var a = 10;
var b = 10;
console.log(`JavaScript first appeared ${a+b} years ago. Crazy!`);
//=> JavaScript first appeared 20 years ago. Crazy!
warning! this does not work with links.
var variable = 'variable',
another = 'another';
['I would', 'like to'].join(' ') + ' a js ' + variable + ' together with ' + another + ' to create ' + [another, ...[variable].concat('name')].join(' ').concat('...');
You can use the JavaScript String concat() Method,
var str1 = "Hello ";
var str2 = "world!";
var res = str1.concat(str2); //will return "Hello world!"
Its syntax is:
string.concat(string1, string2, ..., stringX)
if you want to concatenate the string representation of the values of two variables, use the + sign :
var var1 = 1;
var var2 = "bob";
var var3 = var2 + var1;//=bob1
But if you want to keep the two in only one variable, but still be able to access them later, you could make an object container:
function Container(){
this.variables = [];
}
Container.prototype.addVar = function(var){
this.variables.push(var);
}
Container.prototype.toString = function(){
var result = '';
for(var i in this.variables)
result += this.variables[i];
return result;
}
var var1 = 1;
var var2 = "bob";
var container = new Container();
container.addVar(var2);
container.addVar(var1);
container.toString();// = bob1
the advantage is that you can get the string representation of the two variables, bit you can modify them later :
container.variables[0] = 3;
container.variables[1] = "tom";
container.toString();// = tom3

How do I interpolate a variable as a key in a JavaScript object?

How can I use the value of the variable a as a key to lookup a property? I want to be able to say: b["whatever"] and have this return 20:
var a = "whatever";
var b = {a : 20}; // Want this to assign b.whatever
alert(b["whatever"]); // so that this shows 20, not `undefined`
I am asking if it's possible during the creation of b, to have it contain "whatever":20 instead of a:20 where "whatever" is itself in a variable. Maybe an eval could be used?
This works in Firefox 39 and Chrome 44. Don't know about other browsers. Also it doesn't work in nodejs v0.12.7.
var a = "whatever";
var b = { [a]: 20 };
console.log(b["whatever"]); // shows 20
That is, to interpolate a variable, enclose it in brackets.
I'm not sure if this is a part of any standard. Originally, I saw such syntax here: https://hacks.mozilla.org/2015/07/es6-in-depth-classes/ where the author defined:
[functionThatReturnsPropertyName()] (args) { ... }
I'm also not sure if you should use that syntax. It's not widely known. Other members on your team might not understand the code.
var a = "whatever";
var b = {};
b[a] = 20;
alert(b["whatever"]); // shows 20
var a = "whatever";
var b = {a : 20};
b[a] = 37;
alert(b["whatever"]); // 37
'a' is a string with the value 'a'. a is a variable with the value 'whatever'.
Great question. I had a time trying to figure this out with underscore but the answer couldn't be more simple:
var a = "whatever";
var b = {a : 20};
var array = [a, b]
var answer = _.object([[array]])// {whatever: {a:20}}//NOTICE THE DOUBLE SET OF BRACKETS AROUND [[array]]
I hope this helps!
Try this:
var a = "whatever";
var c = "something";
var b = {whatever : 20, something: 37};
alert(b[a]); // Shows 20
alert(b[c]); // Shows 37
Here is the fiddle.
Or if I understand from the below comments correctly, try this:
var a = "whatever";
var b = {a : 20};
alert(b.a); // Shows 20
To show all options, I want mention the CoffeeScript way of doing this, which is:
var a = "whatever";
var b = (
obj = {},
obj["" + a] = 20,
obj
);
alert(b.whatever); // 20
Although I prefer:
var a = "whatever";
var b = {};
b[a] = 20;
alert(b.whatever); // 20

Categories

Resources