You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在JavaScript中基于里程计算的for循环结果创建关联数组

解决方案:将Distance Matrix结果转换为关联数组

Got it, let's tackle this! You want to convert the Google Maps Distance Matrix results into an associative (key-value) array so you can easily access pairs like {目的地: 英里数} for other functions. Here's how to modify your existing code to achieve this:

修改后的代码

function calcDistance(response, status) {
  if (status != google.maps.DistanceMatrixStatus.OK) {
    alert('Error was: ' + status);
  } else {
    var origins = response.originAddresses;
    var destinations = response.destinationAddresses;
    
    // 1. 创建空的关联数组存储目的地与英里数
    const destinationToMileage = {};
    // 可选:创建数组存储完整行程信息(起点、距离、耗时)
    const allTripDetails = [];

    for (var i = 0; i < origins.length; i++) {
      var results = response.rows[i].elements;
      const currentOrigin = origins[i];
      
      for (var j = 0; j < results.length; j++) {
        const currentDest = destinations[j];
        const distanceText = results[j].distance.text;
        const durationText = results[j].duration.text;
        
        // 提取英里数的数值(去掉" mi"后缀,支持小数)
        const mileageValue = parseFloat(distanceText.split(' ')[0]);

        // 填充关联数组:目的地为键,英里数为值
        destinationToMileage[currentDest] = mileageValue;

        // 填充完整行程信息(按需使用)
        allTripDetails.push({
          origin: currentOrigin,
          destination: currentDest,
          mileage: mileageValue,
          fullDistanceText: distanceText,
          fullDurationText: durationText
        });

        // 保留原有的页面输出逻辑
        outputDiv.innerHTML += `${currentOrigin} to ${currentDest}: ${distanceText} in ${durationText}<br>`;
      }
    }

    // 测试输出:查看关联数组结构
    console.log('目的地-英里数关联数组:', destinationToMileage);
    // 测试输出:查看完整行程信息
    console.log('全部行程详情:', allTripDetails);

    // 示例:传递给其他函数使用
    // useMileageData(destinationToMileage);
  }
}

关键细节说明

  • 提取英里数:distanceText.split(' ')[0] 将类似 "177 mi" 的文本拆分为数组 ["177", "mi"],取第一个元素后用 parseFloat 转换为数字(支持像 21.8 这样的小数)。
  • 关联数组使用:destinationToMileage 就是你需要的结构:{"Margate, UK": 177, "Brighton, UK": 158, ...}。你可以直接通过键名访问值,比如 destinationToMileage["Margate, UK"]。
  • 完整行程存储:如果需要保留起点、耗时等额外信息,allTripDetails 数组存储了每个行程的对象,方便后续更复杂的操作。

示例:在其他函数中调用关联数组

// 示例函数:处理英里数数据
function useMileageData(mileageArray) {
  // 获取单个目的地的英里数
  console.log('Brighton到起点的英里数:', mileageArray["Brighton, UK"]); // 输出158

  // 遍历所有目的地和对应的英里数
  for (const [destination, miles] of Object.entries(mileageArray)) {
    console.log(`${destination}: ${miles} 英里`);
  }
}

内容的提问来源于stack exchange,提问作者Sam Skirrow

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.30 23:42:44