javascript - 在 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);
解决方案
您在循环之外只看到一个值的原因是因为每次循环时都会为 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);
推荐阅读
- sql - 如何在 SQL 中将 varchar2 转换为数字
- sql - 从 SQLite 数据库中获取时尝试/除了不工作
- c - 在函数中引用指针有什么区别
- ios - 如何在 Swift 中使用共享容器/应用程序组从其他目标访问文件
- tensorflow - keras.utils.Sequence 与多个文件
- python - 如何正确读取 csv 文件并返回数据以用于其他功能
- python - 尝试用树枝为不断增长和收缩的细丝设置动画
- qt - 如何在windows上制作qmake生成的Makefile?(nmake 和 mingw-make)
- python - 在字符串中查找连续的字母
- javascript - 以数组作为输入参数实现斐波那契