为什么它不断多次遍历数组元素

Why it keeps iterating through the array elements multiple times?

本文关键字:遍历 数组元素 为什么      更新时间:2023-09-26

我正在尝试使用"标题元素"从数组中输出所有值 有 10 个值 - 标题。问题:

  1. 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);
    }
}