I think it's fairly clear what I want to do here:
var viewnames = {};
viewnames['region-a'] = "Region A";
viewnames['region-b'] = "Region B, partial";
viewnames['region-c'] = "Region C";
function loadView(view_name) {
alert('view_name: ' + view_name);
alert('viewname: ' + viewnames.view_name);
document.getElementById("viewtitle").innerText = view_name;
}
But if I call this with view_name as region-a the alert says viewnames.view_name is undefined. What is the problem?
You must use viewnames[view_name] inside your function loadView
You need to index it by name, e.g. viewnames[view_name]
Access it by associative array index (viewnames[view_name]). Please DO NOT use an eval construct (eval("var tmp = viewnames." + view_name + ";")).
Related
Suppose I need to declare a JavaScript variable based on a counter, how do I do so?
var pageNumber = 1;
var "text"+pageNumber;
The above code does not work.
In JavaScript (as i know) there are 2 ways by which you can create dynamic variables:
eval Function
window object
eval:
var pageNumber = 1;
eval("var text" + pageNumber + "=123;");
alert(text1);
window object:
var pageNumber = 1;
window["text" + pageNumber] = 123;
alert(window["text" + pageNumber]);
How would you then access said variable since you don't know its name? :) You're probably better off setting a parameter on an object, e.g.:
var obj = {};
obj['text' + pageNumber] = 1;
if you -really- want to do this:
eval('var text' + pageNumber + '=1');
I don't think you can do it sing JavaScript.I think you can use an array instead of this,
var textArray=new Array();
textArray[pageNumber]="something";
Assuming that the variable is in the global scope, you could do something like this:
var x = 1;
var x1 = "test"
console.log(window["x" + x]); //prints "test"
However, a better question might be why you want such behaviour.
You could also wrap your counter in an object:
var PageNumber = (function() {
var value = 0;
return {
getVal: function(){return value;},
incr: function(val){
value += val || 1;
this['text'+value]=true /*or some value*/;
return this;
}
};
})();
alert(PageNumber.incr().incr().text2); //=>true
alert(PageNumber['text'+PageNumber.getVal()]) /==> true
It can be done using this keyword in JS:
Eg:
var a = [1,2,3];
for(var i = 0; i < a.length; i++) {
this["var" + i] = i + 1;
}
then when you print:
var0 // 1
var1 // 2
var2 // 3
I recently needed something like this.
I have a list of variables like this:
var a = $('<div class="someHtml"></div>'),b = $('<div class="someHtml"></div>'),c = $('<div class="someHtml"></div>');
I needed to call them using another variable that held a string with the name of one of these variables like this:
var c = 'a'; // holds the name of the wanted content, but can also be 'b' or 'c'
$('someSelector').html(eval(c)) // this will just use the content of var c defined above
Just use eval to get the variable data.
I just did
I know a lot of the other answers work great, such as window["whatever"] = "x"; but I will still put my own answer here, just in case it helps.
My method is to use Object.assign:
let dict = {};
dict["test" + "x"] = "hello";
Object.assign(window, dict)
a little improvement over bungdito's answer, use the dynamic variable dynamically
var pageNumber = 1;
eval("var text" + pageNumber + "=123456;");
eval(`alert(text${pageNumber})`);
note: usage of eval is strongly discourgae
first time using stackoverflow. :)
I am a beginner in JS trying to add values to a list of variables that may change based on the number of passengers variable. (ie. if numRiders = 4 I need to assign values to passenger1Name, passenger2Name, passenger3Name, passenger4Name)
I am trying to use eval inside a loop to do it:
for(i = 0; i<=numRiders; i++) {
j = i+1
var l ='var '
var k = 'passenger'
let nameJ = ride[i].passengerDetails.first + ' ' + ride[i].passengerDetails.last;
console.log (nameJ)
eval(l+k+j+ 'Name' + '= ' + nameJ + ';')
console.log(passenger1Name)
I am getting this output right after the nameJ console.log
VM321:1 Uncaught SyntaxError: Unexpected identifier
at pageLoad
Anyone know how can I solve this or approach this differently? Unfortunately, I can't change the variables names (e.g. passengerXName) to one that would make it easier to assign dynamic variables.
Thank you
nameJ appears to be a string. So you need to put quotes around it.
eval(l+k+j+ 'Name' + '= "' + nameJ + '";')
But as others stated in the comments, defining variables dynamically like this is almost never what you really want.
I have since 1996 or so RARELY seen any reason for eval
This is recommended
const rides = [
{ passengerDetails: {first:"Fred",last:"Flinstone"}},
{ passengerDetails: {first:"Wilma",last:"Flinstone"}}
]
const names = rides.map(ride => `${ride.passengerDetails.first} ${ride.passengerDetails.last}`)
console.log(names)
or even
const rides = [
{ passengerDetails: {first:"Fred",last:"Flinstone"}},
{ passengerDetails: {first:"Wilma",last:"Flinstone"}}
]
const names = rides.reduce((acc,ride,i) => {
acc[`passenger${i+1}name`] = `${ride.passengerDetails.first} ${ride.passengerDetails.last}`
return acc;
},{})
console.log(names)
If you MUST, try this assuming you have a window scope to add it to
const rides = [
{ passengerDetails: {first:"Fred",last:"Flinstone"}},
{ passengerDetails: {first:"Wilma",last:"Flinstone"}}
]
rides.forEach((ride,i) => {
let nameJ = `${ride.passengerDetails.first} ${ride.passengerDetails.last}`;
window[`passenger${i+1}Name`]=nameJ;
})
console.log(passenger1Name)
The option from #ZacAnger
var names = {};
for(i = 0; i<=numRiders; i++) {
j = i+1
let nameJ = ride[i].passengerDetails.first + ' ' + ride[i].passengerDetails.last;
names['passenger'+ j+ 'Name'] = nameJ;
}
For some reason the keyText variable isn't showing any value when it should concat for each variable in keywords.
When someone clicks the button it runs addKeyword and grabs the value of the input.
Tried to Console.Log the keyText variable and didn't work at all.
var keywords = [];
var keyText = "";
function addKeyword() {
var keywordName = document.getElementById("keywordAdd").value
keywords.push(keywordName);
keywords.forEach(showKeywords);
function showKeywords(item, index) {
var newString = "<span class='keyword' onclick='delKeyword(" + index + ")'>✖ " + item + "</span>";
keyText.concat(newString);
document.getElementById("keywords").innerHTML = keyText;
}
}
No Errors shown in Console. Expected result is a list of but doesn't show.
The problem is that .concat doesn't mutate the string, it returns a new string.
You need to do something like this:
keyText = keyText.concat(newString);
By the way, your current approach is not that efficient because it changes the element's inner HTML at each iteration. You should probably do that only once after the HTML for all the elements is generated. Here is another approach that does that:
const result = keywords.map((item, index) => (`<span class="keyword" onclick="delKeyword(${index})">✖ ${item}</span>`)).join('');
document.getElementById("keywords").innerHTML = result;
Titus answer is correct, but you can simply use :
keyText += newString;
I have a problem to manipulate checkbox values. The ‘change’ event on checkboxes returns an object, in my case:
{"val1":"member","val2":"book","val3":"journal","val4":"new_member","val5":"cds"}
The above object needed to be transformed in order the search engine to consume it like:
{ member,book,journal,new_member,cds}
I have done that with the below code block:
var formcheckbox = this.getFormcheckbox();
formcheckbox.on('change', function(checkbox, value){
var arr=[];
for (var i in value) {
arr.push(value[i])
};
var wrd = new Array(arr);
var joinwrd = wrd.join(",");
var filter = '{' + joinwrd + '}';
//console.log(filter);
//Ext.Msg.alert('Output', '{' + joinwrd + '}');
});
The problem is that I want to the “change” event’s output (“var filter” that is producing the: { member,book,journal,new_member,cds}) to use it elsewhere. I tried to make the whole event a variable (var output = “the change event”) but it doesn’t work.
Maybe it is a silly question but I am a newbie and I need a little help.
Thank you in advance,
Tom
Just pass filter to the function that will use it. You'd have to call it from inside the change handler anyway if you wanted something to happen:
formcheckbox.on('change', function(cb, value){
//...
var filter = "{" + arr.join(",") + "}";
useFilter(filter);
});
function useFilter(filter){
// use the `filter` var here
}
You could make filter a global variable and use it where ever you need it.
// global variable for the search filter
var filter = null;
var formcheckbox = this.getFormcheckbox();
formcheckbox.on('change', function(checkbox, value){
var arr = [],
i,
max;
// the order of the keys isn't guaranteed to be the same in a for(... in ...) loop
// if the order matters (as it looks like) better get them one by one by there names
for (i = 0, max = 5; i <= max; i++) {
arr.push(value["val" + i]);
}
// save the value in a global variable
filter = "{" + arr.join(",") + "}";
console.log(filter);
});
I have an object 'res' and it holds a field:
res.headers=new object();
im using this field as a map which holds key and value meaning:
res.headers['key']='value';
is there any way to get the content of this map by iterating it without knowing the key?
thank you!
for(var key in res.headers) {
if(res.headers.hasOwnProperty(key)) {
console.log(key + " -> " + res.headers[key]);
}
}
or with Object.keys():
for(var key in Object.keys(res.headers)) {
console.log(key + " -> " + res.headers[key]);
}
Easiest thing to do is use a javascript library, like underscore for example, then use someting like:
arr = _.values(res.headers)
arr[0] // value of first element