0

I am wondering how to pass a variable between 2 functions.

I have looked on Stackoverflow but all examples I tried did not work for me.

I have function, which calculates an array: arrR.

Now, I would like to call this variable somewhere else:

function my_function(arrR) {
    return(arrR[1]);
}

function onRefresh(chart) {
    chart.config.data.datasets.forEach(function(dataset) {
        dataset.data.push({
            x: Date.now(),
            y: myfunction(arrR)
        });
    });
}

But y: myfunction(arrR) gives notting. I have checked that if I put some number say y: 1 this works.

Any clue ?

Many thanks

4 Answers4

0

Can you get the value of the variable arrR?

If the scope of the variable arrR is different from onRefresh one level or higher. You can't get arrR across domains. You need to understand the scope of JavaScript

Bhargav Rao
  • 50,140
  • 28
  • 121
  • 140
  • Yes I think so as alert(arrR[1]); gives the correct value –  Jun 03 '20 at 08:29
  • If the scope of the variable arrR is different from onRefresh one level or higher. You can't get arrR across domains. You need to understand the scope of JavaScript – GreenKing19 Jun 03 '20 at 08:42
  • Ok. I understand I need to understand the scope of JavaScript. I have declared now `var arrR = [];` but it still does not work. –  Jun 03 '20 at 08:46
0

Try this instead. Also check if arrR is exist or not by using console.log()

function onRefresh(chart) {
    chart.config.data.datasets.forEach(function(dataset) {
        arrR.length > 0 && dataset.data.push({
            x: Date.now(),
            y: myfunction(arrR)
        });
    });
}
0

your arrR variable is inside a function. It might be that the scope of that variable will be inside the function only.Try declaring this variable outside the function to use it globally.Hope it helps.:)

0

Thanks everyone. This works now like: I just had to declare the variable outside functions.


var arrR = [];