简体   繁体   English

从for循环结果在javascript中创建一个关联数组

[英]Create an associative array from for loop results in javascript

I have a form that calculates mileage from 4 destinations to one single origin.我有一个表格可以计算从 4 个目的地到一个单一起点的里程数。 When submitted, I can display the text that shows the origin and the distance to each destination on a new line, for example:提交后,我可以在新行上显示显示起点和到每个目的地的距离的文本,例如:

Margate, UK to Coventry, UK: 177 mi in 3 hours 13 mins Brighton, UK to Coventry, UK: 158 mi in 2 hours 41 mins Bristol, UK to Coventry, UK: 108 mi in 1 hour 49 mins Birmingham, UK to Coventry, UK: 21.8 mi in 31 mins英国马盖特到英国考文垂:177 英里,3 小时 13 分钟英国布莱顿到英国考文垂:158 英里,2 小时 41 分钟英国布里斯托尔到英国考文垂:108 英里,1 小时 49 分钟英国伯明翰到考文垂,英国:31 分钟内 21.8 英里

I want to create an array of this information so I can call it in other functions.我想创建一个包含这些信息的数组,以便我可以在其他函数中调用它。 For example, I just want the Destination and the miles, so something like this:例如,我只想要目的地和里程,所以是这样的:

{"Margate, UK" => 177, "Brighton, UK" => 158, "Bristol, UK" => 108, "Birmingham, UK" => 21.8} {“英国马盖特”=> 177,“英国布莱顿”=> 158,“英国布里斯托尔”=> 108,“英国伯明翰”=> 21.8}

Here is the code I use to make the for loop:这是我用来制作 for 循环的代码:

function calcDistance(response, status) {
  if (status != google.maps.DistanceMatrixStatus.OK) {
    alert('Error was: ' + status);
  } else {
    var origins = response.originAddresses;
    var destinations = response.destinationAddresses;

    for (var i = 0; i < origins.length; i++) {
      var results = response.rows[i].elements;
      for (var j = 0; j < results.length; j++) {

    outputDiv.innerHTML += origins[i] + ' to ' + destinations[j]
                + ': ' + results[j].distance.text + ' in '
                + results[j].duration.text + '<br>';

      }
    }
  }
}

You can try making an array const distances = [] and then push into it the desired information in the inner for loop您可以尝试创建一个数组const distances = []然后将内部 for 循环中的所需信息推入其中

...
var results = response.rows[i].elements;
for (var j = 0; j < results.length; j++) {
  distances.push([origins[i], results[j].distance.text])
  ...
}

or you could extract the information from the submitted form text using regex或者您可以使用正则表达式从提交的表单文本中提取信息

 const distinations = 'Margate, UK to Coventry, UK: 177 mi in 3 hours 13 mins Brighton, UK to Coventry, UK: 158 mi in 2 hours 41 mins Bristol, UK to Coventry, UK: 108 mi in 1 hour 49 mins Birmingham, UK to Coventry, UK: 21.8 mi in 31 mins' const cities = distinations.match(/\\b(?:(?!Coventry)\\w)\\w+, \\w+/g) const distances = distinations.match(/(?<=: )\\d+/g) const result = [] for (let index in cities) { const city = cities[index] const distance = distances[index] result.push({ city, distance }) } console.log(result)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM