javascriptarraysstringsplitindefinite

Splitting string results in infinite loop


I need to split this string and loop through the resulting array. However, even though my result string array has only 3 items, my loop goes to infinity.

I am probably missing something, but I can not see it at this point.

Here is the code:

CustomizeDashboardService.getCustomizedDashboard().then(function (res) {
            console.log(res);


            var sensors = res.sensor.split(',');
            var devices = res.uuid.split(',');;

            console.log("CS: S",sensors)   // I Can see these 2 arrays have only 3 items each,
            console.log("CS: D",devices)   //  but when it goes into my for loop, it iterates to indefinite

            for(i=0;i<devices.length-1;i++){
                console.log("girdi")  // I see this is logging more than 1000 times

                var index = findIndex(devices[i]);

                var obj = {
                    device:self.deviceList[index],
                    sensor: sensors[i]
                }

                self.customizedSensors.push(obj);


            }



            console.log("customized sensors",self.customizedSensors);


        })

Solution

  • Your loop has for(i=0;i<devices.length-1;i++) which means the iteration variable is not locally scoped. If somewhere else the i value is changed then it can cause issues. As a matter of habit, always var your iterator variable unless you have a very specific reason not to (such situations do exist but are fairly rare). To avoid other issues I would recommend looking through all of your code and making sure you have the var in there.