简体   繁体   中英

How to access a variable value that is defined inside another function JS

I have a variable totalActivatedOffers which is defined inside a function, inside an IF statement. I need to be able to use the value of this variable outside of the IF statement by another function but can't get it to work, it keeps returning undefined.

I've declared it at the top of the script block like this:

var totalActivatedOffers;

But still no joy. Here is an example of how the value is assigned to it (simplified for illustration):

if ("SSO" in sessionStorage) {
  setTimeout(function(){
    if (firstArrayLength.length == 3) {
      var totalActivatedSparksOffers = 4;
    }
    if (secondArrayLength.length == 3) {
      var totalActivatedRewardsOffers = 7;
    }
    var totalActivatedOffers = totalActivatedSparksOffers + totalActivatedRewardsOffers;
  }, 2500) 
} // closes if SSO is inside session storage

// need to access the value here, outside of the IF statement
console.log('Total activated offers to subtract is ' + totalActivatedOffers);

Any help would be greatly appreciated.

SOLUTION:

Managed to get around the issue by making it a window variable like this:

window.totalActivatedOffers = totalActivatedSparksOffers + totalActivatedRewardsOffers;

通过将其设置为窗口变量来设法解决该问题:

window.totalActivatedOffers = totalActivatedSparksOffers + totalActivatedRewardsOffers;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM