【发布时间】:2017-04-10 21:48:00
【问题描述】:
我需要拆分这个字符串并循环遍历结果数组。然而,即使我的结果字符串数组只有 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);
})
【问题讨论】:
-
devices.length-1带给你什么? -
for(i=0;i<devices.length-1;i++)必须是for(var i=0;i<devices.length;i++)才能遍历整个数组,还是只遍历前 2 个元素(如果有 3 个元素)? -
我的直觉是,由于您使用的是
for(i=0;...)而不是for(var i = 0;...),所以i是一个全局变量,并且正在代码中的其他位置重置。 -
是的,我只需要前 2 个,这就是我做 length-1 的原因
-
@MustafaBereket 好的,比您在这部分代码中只错过了
var i = 0;
标签: javascript arrays string split indefinite