我有一个变量totalActivatedOffers,它在IF语句中的函数中定义。我需要能够通过另一个函数在IF语句之外使用这个变量的值,但无法使其工作,它一直返回未定义的值。
我在脚本块的顶部声明如下:
var totalActivatedOffers;
但仍然没有快乐。以下是如何将值分配给它的示例(为了说明起见,进行了简化(:
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);
如有任何帮助,我们将不胜感激。
解决方案:
设法通过将其作为窗口变量来解决这个问题,如下所示:
window.totalActivatedOffers = totalActivatedSparksOffers + totalActivatedRewardsOffers;
通过将其作为窗口变量来解决问题:
window.totalActivatedOffers = totalActivatedSparksOffers + totalActivatedRewardsOffers;