Variable Name as a String in JavaScript

Variable name as a string in Javascript

Typically, you would use a hash table for a situation where you want to map a name to some value, and be able to retrieve both.

var obj = { myFirstName: 'John' };

obj.foo = 'Another name';

for(key in obj)

console.log(key + ': ' + obj[key]);

get variable name into string in javascript

Use the code below.

const abc = '123';

const def = '456';

const varToString = varObj => Object.keys(varObj)[0]

alert ("value of " +varToString({def}) +" is "+ def +" and value of " +varToString({abc})+" is "+abc );

Convert string to variable name in JavaScript

If it's a global variable then window[variableName]
or in your case window["onlyVideo"] should do the trick.

Set string to variable name

You can store the data in an object with the keys matching your select's values.

var data = {
basketball: "changeable-string",
handball: 760,
football: null,
baseball: "description: ball-game to play"
}

function myFunction(el) {
console.log(data[el.value])
}
<select name="box" onchange="myFunction(this);">
<option value="football">Football</option>
<option value="handball">Handball</option>
<option value="basketball">Basketball</option>
<option value="baseball">Baseball</option>
</select>

Check if a string is same as a variable name

You can iterate through the keys of this and check for a var name

var x = "news"

var news = ["1", "2", "3"]

function varNameExists(varName){

return [...Object.keys(this)].some(name => name === varName)

}

console.log(varNameExists(x))

How to make string act like a variable name?

Specify the dictionary first

Then you can take id's object... /p>

const dictionary = {
id1: {name: 'xxxx'},
id2: {name: 'yyyy'},
id3: {name: 'zzzz'},
};

const myfunc = (item)=>{
const idName = item.id;
const aName = dictionary[idName];
console.log(aName.name);
};
<div id="id1" onclick="myfunc(this)">one</div>
<div id="id2" onclick="myfunc(this)">one but 2</div>
<div id="id3" onclick="myfunc(this)">the third</div>

Javascript: Reference a variable name from the variable itself

The reason it doesn't work is because the variable foo is not accessable to the function varlog! foo is declared in someRandomFunction, and is never passed into varlog, so varlog has no idea what the variable foo is! You can solve this problem by passing the variable foo into the function(or using some sort of closure to make foo in the scope of varlog) along with its string representation, but otherwise, I think you are out of luck.

Hope this helps.



Related Topics



Leave a reply



Submit