This question already has an answer here:
variable scope in d3 javascript
(1 answer)
Closed 7 years ago.
I have a global variable say :
var series,hours;
var loadData = function(){
series = [[]];
hours = [];
d3.json("data/radar.json", function(error, data) {
data.QualitySummaryObject.forEach(function(d,i) {
series[i] = d.extractPercentage;
hours[i] = d.extractorName;
});
});
console.log(hours);
};
Now if I am trying to access this console.log its working fine, but.
var print = function(){
console.log(hours); //here its not working no value in hours why ... ?
}
Ensure that you hours is global:
window.hours = [];
Then anywhere you can log it:
console.log(window.hours);
Using directly var without declaration will avoid context problems.
If you are running the above code in a function, the variable hours is not a global variable because you previously declared it with var.
If you want to declare a variable as a global variable, instead of this:
var hours = [];
Do this:
hours = [];
To declare a global variable, all you have to do is give it a name.
Related
I am quite confused to understand the logic in my question as i"m new to javascript but i tried to write some logic mentioned below but unable to understand what logic to write exactly to get the result. If someone can please help me in rectifying my code and help me understand to get the result.
JS
// Global Variable
var a = 40;
var b = 70;
function var_ops_5() {
// Local Variable
var a = 4;
var b = 7;
var c = a + b;
var d = a * b;
var e = a % c;
};
Using var is the problem. You can't have var = 40 and then have var a = 4 inside a block because with var, variables declared inside a block can be accessed from outside the block. The var a = 4 inside your function overwrites var = 40. If you change them to let keyword it should work as intended.
This question already has answers here:
Use dynamic variable names in JavaScript
(19 answers)
Closed last year.
I have some js code like this:
var parameter0 = 12345;
var parameter1 = 54321;
var parameter2 = 33333;
var parameter3 = 99990;
function selectValue(number) {
alert(parameter+number);
}
selectValue(2);
Here is a fiddle - https://jsfiddle.net/frwd2qLg/
This code will not work, because, for example, for number = 2, it will not show 33333, but will be undefined. Any workaround?
As people said in your comments, you could use an array or an object to do this task. But answering your question you culd use an eval to access the variable name.
var parameter0 = 12345;
var parameter1 = 54321;
var parameter2 = 33333;
var parameter3 = 99990;
function selectValue(number) {
alert(eval("parameter"+number));
}
selectValue(2);
This question already has answers here:
Javascript: How to use Template Literals with JSON?
(4 answers)
Closed 2 years ago.
I am having the object config and when I fetch the config["RegionId"], it will give me ${Region}. Now I want to fetch the value of Region. As I have got ${Region}, I thought I could do console.log(`${val}`) to get 'abc'. But it is not working.
How to get this? This is what I have tried,
var config = {
"RegionId" : "${Region}"
}
var Region = 'abc'
var val = config['RegionId']
console.log(`${val}`)
Don't put double quotes around the property value. Use back-ticks (for template literal strings) as you are doing for val. And make sure you've declared Region prior to attempting to access it.
var Region = 'abc';
var config = {
"RegionId" : `${Region}`
};
var val = config['RegionId'];
console.log(`${val}`);
And while your question is centered around template literals, I hope you know that for this scenario, they add no value and are overkill. Here's the same thing with regular strings variables:
var Region = 'abc';
var config = {
"RegionId" : Region
};
console.log(config['RegionId']);
try using eval function
var config = {
"RegionId" : "${Region}"
}
var Region = 'abc'
var val = config['RegionId']
console.log(eval("`"+val+"`"));
I have variable "a" and variable "cm", both declared in the same scope.
But inside each loop, variable a is accessible, while cm is not accessible:
var a = [];
var sm = grid.getSelectionModel();
var cm = grid.getColumnModel();
Ext.each(sm.getSelections(), function (item, index) {
var s = 'test';
a.push(s); //it works, a is accessible
var colHeader = cm.getColumnHeader(index); //Uncaught ReferenceError: cm is not defined
});
why? How can I access cm inside each loop?
This is documentation of grid.getColumnModel:
ExtJsGrid
cm should be accessible in the code that you gave. You can verify that by doing console.log(cm); right before you get the error.
The issue is most likely that the getColumnHeader function doesn't exist on cm.
This question already has answers here:
Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference
(7 answers)
Closed 7 years ago.
I am trying to pass two values to a function from two async functions and I am not sure how to proceed. Here is the code:
var btcPriceInUSD;
var priceExchangeMXN;
var btcLink = "https://blockchain.info/ticker";
var exchangeRateLink = "http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.xchange%20where%20pair%20in%20%28%22USDMXN%22%29&env=store://datatables.org/alltableswithkeys&format=json";
//Get btc price in USD
$.getJSON(btcLink, function(btcData)
{
btcPriceInUSD = btcData.USD.last;
//document.write(btcPriceInUSD);
});
//Get current USD/MXN exchange rate
$.getJSON(exchangeRateLink, function(exchangeData)
{
priceExchangeMXN = exchangeData.query.results.rate.Rate;
//document.write(priceExchangeMXN);
});
//Convert btc price to MXN
function convertToMXN(btc,toMXN){
var result = parseFloat(btc) * parseFloat(toMXN);
document.write(result);
}
convertToMXN(btcPriceInUSD,priceExchangeMXN)
I know the issue is that I am calling the function outside of the async ones so it is not recieving the numbers and it is giving me a NAN (not a number) but I don't know how I would correctly pass those two parameters that are each retrieved in different functions, is it possible to combine the btcPriceInUSD and priceExchangeMXN in one and call it from there?
Thanks in advance!
Try using $.when() , .then() , substituting returning value at complete function for declaring variables outside scope of asynchronous functions ; also adding an error handler
$.when($.getJSON(btcLink, function(btcData) {
return btcData.USD.last
})
, $.getJSON(exchangeRateLink, function(exchangeData) {
return exchangeData.query.results.rate.Rate
}))
.then(convertToMXN, function err() {console.log(arguments)})
try this (simply chaining the ajax calls and finally calling the method when both values are available)
var btcPriceInUSD;
var priceExchangeMXN;
var btcLink = "https://blockchain.info/ticker";
var exchangeRateLink = "http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.xchange%20where%20pair%20in%20%28%22USDMXN%22%29&env=store://datatables.org/alltableswithkeys&format=json";
//Get btc price in USD
$.getJSON(btcLink, function(btcData)
{
btcPriceInUSD = btcData.USD.last;
//document.write(btcPriceInUSD);
//Get current USD/MXN exchange rate
$.getJSON(exchangeRateLink, function(exchangeData)
{
priceExchangeMXN = exchangeData.query.results.rate.Rate;
//document.write(priceExchangeMXN);
convertToMXN(btcPriceInUSD,priceExchangeMXN);
});
});
//Convert btc price to MXN
function convertToMXN(btc,toMXN){
var result = parseFloat(btc) * parseFloat(toMXN);
document.write(result);
}