Question

according to my knowledge, this feature already exists in PHP. lets look at the following php code:

$color = 'red';
$$color = 'dark';

description of the feature:

Sometimes it is convenient to be able to have variable variable names. That is, a variable name which can be set and used dynamically.A variable variable takes the value of a variable and treats that as the name of a variable. In the above example, red, can be used as the name of a variable.At this point two variables have been defined and stored in the PHP symbol tree: $color with contents "red" and $red with contents "dark".

my Question

can this be done in java Script?

Was it helpful?

Solution

var color = 'red';
window[color] = 'dark';
console.log(color, red);

OTHER TIPS

Three different techniques come to mind, each with its warnings and (except the second one) uses:

1) You can declare a new variable in JavaScript anywhere in the code using the var keyword:

var $color = 'red';

The variable is actually defined throughout the scope in which the var occurs, even above the var statement — that is, these two functions are identical even though they look slightly different:

function foo() {
    doSomething();
    var x = 5;
    x += doSomethingElse();
    return x;
}

function foo() {
    var x;

    doSomething();
    x = 5;
    x += doSomethingElse();
    return x;
}

This is because all vars take effect when the context for the function is created, not where they appear in the code. More: Poor, misunderstood var

2) If you just assign to a free symbol that's never been declared anywhere, you'll create an implicit global variable (not one constrained to the current scope), which is generally a bad idea. More: The Horror of Implicit Globals

3) Another thing you can do is have an object which is a container for various variables you want to track. You can create new properties on the object just by assigning them:

var data = {};    // A blank object
data.foo = "bar"; // Now `data` has a `foo` property

This technique is particularly handy when you need to track data that your script is completely unaware of, for instance based on user input, because you can use either dotted notation and a literal as above (data.foo), or you can use bracketed notation and a string (data["foo"]). In the latter case, the string can be the result of any expression, so all of these create a foo property on data:

// Dotted notation with a literal
data.foo = 42;

// Bracketed notation with a literal string
data["foo"] = 42;

// Bracketed notation with a string coming from a variable
s = "foo";
data[s] = 42;

// Bracketed notation with a string coming from an expression
s = "o";
data["f" + s + s] = 42;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top