I have an setInterval in which there is a condition that defines the array ta
. The array is defined for the first time the condition is met, but when the condition is not met, I want to keep the same amount of the first array as given, but for the second time, when the condition is not met, the ta
array is not defined. How can I solve this problem?
var a=1; setInterval(() => { if (a==1){ var ta=[]; for(let i=1;i<3;i++){ ta.push(i); }; console.log(ta); console.log("ta"); a=2; } console.log(ta); // why this is undefined in Second round onwards? },5000);
Put your array ta
outside of the setInterval()
, otherwise it won't be accessible
let a = 1 const ta = [] setInterval(() => { if (a === 1) { for (let i = 1; i < 3; i++) ta.push(i) console.log(`ta while equal to 1: ${ta}`) a = 2 } console.log(`ta for every 5s interval: ${ta}`) }, 5000);
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.