为什么它不断多次遍历数组元素
Why it keeps iterating through the array elements multiple times?
我正在尝试使用"标题元素"从数组中输出所有值 有 10 个值 - 标题。问题:
- for 循环输出所有 10 个值,但它再次执行此操作 10 次。
标题 1标题 2标题 3标题 4标题 5标题 6标题 7标题8标题9标题 10
(再次输出10次)
我该如何解决这个问题无法解决它,代码:此函数在数组中添加数据p_marker.push(marker);
。
function placesToVisitMarker(results, status) {
image = 'pin56.png';
console.log(results);
for (var i = 0; i < results.length; i++) {
var marker = new google.maps.Marker({
position: results[i].geometry.location,
map: map,
title: results[i].name,
icon: image
});
distanceService.getDistanceMatrix({
origins: [currentLocation],
destinations: [results[i].geometry.location],
travelMode: google.maps.TravelMode.WALKING
}, callback);
p_marker.push(marker);
}
}
这个函数是我想将标题和距离输出到#list div
function callback(response, status) {
if (status = "OK") {
for (var i = 0; i < p_marker.length; i++) {
$("#list").append(p_marker[i].title + "</br>");
}
//$("#list").append( +" "+ response.rows[0].elements[0].duration.text + "</br>")
} else {
$("#list").append("ERROR" + status);
}
}
您在回调方法中的循环导致了问题,这是可能会有所帮助的解决方案,
在 placesToVisitMarker 中,您为每个 tym 添加一个元素p_marker。然后,在回调中,您将再次循环遍历p_marker的元素。就像,对于 placesToVisitMarker 内部的循环被调用 10 次,对于每个 tym,回调正在添加标题,该标题是 p_marker 具有的元素数的许多倍。你似乎有问题。
以及关于为什么它被打印 10 次的问题:
原因是,您的回调方法的 for 循环指的是p_marker,到调用回调时,p_marker 中有 10 个元素。因此,对于每个回调调用,都会将 10 个标题附加到列表中。
溶液:
您应该删除回调方法中的"for"循环。并赋予"回调"函数对特定"i"值的访问权限,以便将正确的标题附加到列表中。
function placesToVisitMarker(results, status) {
image = 'pin56.png';
console.log(results);
for (var i = 0; i < results.length; i++) {
var marker = new google.maps.Marker({
position: results[i].geometry.location,
map: map,
title: results[i].name,
icon: image
});
p_marker.push(marker);
// use closure here to make the function remember about the 'i'
// else what would happen is by the time callback will be
// called, i value would be 10, so same element
// will get appended again and again.
(function(i) {
distanceService.getDistanceMatrix({
origins: [currentLocation],
destinations: [results[i].geometry.location],
travelMode: google.maps.TravelMode.WALKING
},
function(response, status) {
if (status == "OK") {
$("#list").append(p_marker[i].title + "</br>");
} else {
$("#list").append("ERROR" + status);
}
});
})(i);
}
}
相关文章:
- 在函数中添加数组元素的数值
- 访问JSON对象内部的数组元素
- Mongoose-在更新中删除数组元素
- javascript数组元素是否知道其封闭数组
- 将数组元素附加到FormData dos'不适用于Firefox 15
- 如何使用 document.querySelectorAll 遍历选定的元素
- 如何在javascript中使用click函数选择数组元素
- 如何在JavaScript中剥离数组元素中的非整数
- 消隐数组元素是否生成自己的属性
- 如何使一个Math.random数组元素比另一个数组元素更有可能被选中
- 在Codrops的内容中添加数组元素展开缩略图网格预览
- 如何使用Jquery水平打印表中的数组元素,并在某个元素之后垂直打印
- 如何访问数组中的数组元素(JavaScript)
- 生成ACF标记位置的数组(元素列表后缺少])
- validate.js验证数组元素
- JavaScript Unshift EACH 数组元素
- 循环遍历一组元素 jQuery
- Ruby在遍历函数时尝试存储数组元素
- 在Javascript中遍历JSON数组元素
- 如何循环遍历一组jQuery元素—一次4个