Javascript嵌套For循环数组具有隐藏值

标签 javascript arrays for-loop variable-assignment nested-loops

我一直在使用 javascript 运行一些使用 leaflet.js 库的简单代码(在本例中,特定函数是 mymap.layerPointToLatLng(), here is the documentation )。 我想使用 [[[x,y]],[[x,y]],...] 形式的数据(该格式特定于 leaflet.js 如何处理多边形和多边形,这种格式是我称之为“dim=2”)。我需要将其转换为纬度和经度(因此是前面提到的函数)。因为我经常这样做,所以我编写了一个函数来为我做这件事:

/*-Formatting functions*/
	function coordconvert(mapvar,array,dim){
		var temp1in=[],tempout1=[],temp2out=[];
		if(dim===1){
			for(i=0;i<array.length;i++){
				tempout1[i]=mapvar.layerPointToLatLng(array[i]);
			}
			return tempout1;
		}
		
		else if(dim===2){
			for(i=0;i<array.length;i++){
				temp1in=array[i];//each polygon
				console.log(i);
				console.log(temp1in);
				console.log(tempout1);
				//tempout1=[];//why do I need this line?
				for(j=0;j<temp1in.length;j++){
					console.log(tempout1);
					var checking = mapvar.layerPointToLatLng(temp1in[j]);
					tempout1[j]=mapvar.layerPointToLatLng(temp1in[j]);//each vertex of polygon
					console.log(j);
					console.log(tempout1);
					console.log(checking);
				}
				temp2out[i]=tempout1;//array of polygons
			}
			return temp2out;
		}
		else{
			console.log("Unable to process coordinate conversion on array");
			return
		}
		
	}

但是,“if(dim===2)”部分似乎无法正常工作,因此所有 console.log 行都无法正常工作。 特别是,只有当我取消注释行 //tempout1=[];//why 时,赋值 tempout1[j]=mapvar.layerPointToLatLng(temp1in[j]); 才显得有效我需要这条线吗?.

使用 console.log,并使用 Google Chrome 查看,我得到以下输出:

First few iterations of loop Final iteration of the loop

可以看出,最终迭代的值(一个对象)在被分配任何内容之前就被包含在 tempout1 数组中(我尝试删除 'if( dim===1)' 部分,并重命名 tempout1 变量,但运气不佳),并且被 Chrome 隐藏(?!?!?!);该值在循环期间不会被覆盖(通过比较 console.log(checking)console.log(tempout1) 可以看出。

为什么我每次在嵌套循环运行之前都必须清理变量?为什么最终迭代的值会在任何事情发生之前就进入?

最佳答案

事实证明,解决方案非常简单 - 我没有正确声明循环变量(即 for (var i=o;i<array.length;i++) ,而不是 for (i=o;i<array.length;i++) )我不确定这如何解释 Google Chrome 控制台的行为,但一切之后看起来就稳定多了。

关于Javascript嵌套For循环数组具有隐藏值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47426011/

相关文章:

javascript - 授权登录时 Laravel 超时

javascript - 试图理解闭包。有人可以引导我完成这段代码吗?

matlab - 向量化嵌套循环,其中一个循环变量依赖于另一个

c - 如何在char中使用For循环?

javascript - 如何读取通过 cordova 文件插件写入的对象?

javascript - JQuery:如何使用 FancySelect 插件强制选择选项为 "selected"?

python - Numpy:使用不同的种子多次统一洗牌数组

javascript - 循环到每个元素的 Array 方法

php - 循环遍历 mysqli 结果数组一次以获取所有信息

java - 字符串构建中的逻辑错误