首页 > 解决方案 > 在 for 循环之外获取价值

问题描述

我需要在 a 之外获取 Z 变量的值,for但是当我从循环内部在控制台中打印它时,它会给出正确的值,而我从循环外部打印它时,它会给出一个应该返回的值

fetch('http://open.mapquestapi.com/elevation/v1/profile?key=tHXSNAGXRx6LAoBNdgjjLycOhGqJalg7&shapeFormat=raw&latLngCollection='+profile)
          .then(r => r.json()) 
          .then(data => {
            var Z;
            for(var i=0;i<data.elevationProfile.length;i++){
                //console.log(data.elevationProfile[i].height);
                Z = (data.elevationProfile[i].height);
                //console.log(Z);
                }
                console.log(Z);

标签: javascript

解决方案


您在循环之外只看到一个值的原因是因为每次循环时都会为 Z 分配一个新变量=

尝试将循环外的 Z 设置为数组,并将循环push变量内的 Z 设置为数组

稍后您将能够使用所有值来控制您的数组

像这样的东西:

fetch('http://open.mapquestapi.com/elevation/v1/profile?key=*CENCOREDKEY*&shapeFormat=raw&latLngCollection='+profile)
      .then(r => r.json()) 
      .then(data => {
        var Z=[];
        for(var i=0;i<data.elevationProfile.length;i++){
            //console.log(data.elevationProfile[i].height);
            Z.push(data.elevationProfile[i].height);
            //console.log(Z);
            }
            console.log(Z);

推荐阅读