拆分字符串会导致无限循环
Splitting string results in infinite loop
我需要拆分这个字符串并循环遍历生成的数组。然而,即使我的结果字符串数组只有 3 个项目,我的循环也会进入无穷大。
我可能遗漏了一些东西,但我现在看不到它。
代码如下:
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);
})
你的循环有 for(i=0;i<devices.length-1;i++)
这意味着迭代变量不是局部范围的。如果在其他地方更改了 i
值,则可能会导致问题。作为一个习惯问题,总是 var
你的迭代器变量,除非你有一个非常具体的理由不这样做(这种情况确实存在但相当罕见)。为避免其他问题,我建议您查看所有代码并确保其中包含 var
。
我需要拆分这个字符串并循环遍历生成的数组。然而,即使我的结果字符串数组只有 3 个项目,我的循环也会进入无穷大。
我可能遗漏了一些东西,但我现在看不到它。
代码如下:
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);
})
你的循环有 for(i=0;i<devices.length-1;i++)
这意味着迭代变量不是局部范围的。如果在其他地方更改了 i
值,则可能会导致问题。作为一个习惯问题,总是 var
你的迭代器变量,除非你有一个非常具体的理由不这样做(这种情况确实存在但相当罕见)。为避免其他问题,我建议您查看所有代码并确保其中包含 var
。