我想用for循环定义一个二维数组对象...我的问题我认为我的对象并没有真正得到处理,这里是代码:
var newLoc = [];
var index;
for (index = 0, i < locations.length; i++){
if(i == 0) {
newLoc[i][0] = locations[i][1];
newLoc[i][1] = locations[i][2];
}
else {
if(locations[i][8] == locations[i-1][8]){
newLoc[i-1][0] = (locations[i][1] + locations[i-1][1])/2;
newLoc[i-1][1] = (locations[i][2] + locations[i-2][1])/2;
}
else{
newLoc[i][0] = locations[i][1];
newLoc[i][1] = locations[i][2];
}
}
}
locations数组本身是旧数组,用于存储新数组(newLoc)的数据。位置&#39;存在的数据是坐标纬度和经度。我想我的for循环表单或我如何声明newLoc 2维数组有问题,但我仍然不知道如何修复它。任何帮助赞赏。
答案 0 :(得分:2)
您可以使用代码进行优化。首先,您必须正确初始化循环。然后在循环内部,最好静态分配值,而不是每次只检查一个实现。这应该优化您的代码。旧位置发布可以使以下代码更加优化。
var newLoc = [];
if(locations.length > 0){
for(var j = 0; j < 1; ++j) {
newLoc[j] = [ ];
newLoc[j][0] = locations[0][1];
newLoc[j][1] = locations[0][2];
}
}
for (var i = 1, i < locations.length; i++){
if(locations[i][8] == locations[i-1][8]){
newLoc[i-1][0] = (locations[i][1] + locations[i-1][1])/2;
newLoc[i-1][1] = (locations[i][2] + locations[i-2][1])/2;
}
else{
newLoc[i][0] = locations[i][1];
newLoc[i][1] = locations[i][2];
}
}
答案 1 :(得分:1)
我认为问题是newLoc总是一个1维数组,你在for循环中声明'index'但在正文中使用'i'
var newLoc = [];
// loop with
for (var i = 0; i < locations.length; i++){
//Create the second dimention
newLoc[i] = [];
if(i == 0) {
...
答案 2 :(得分:0)
有一件事我注意到,在你的for
循环中,你写了
for (index = 0, i < locations.length; i++)
而不是
for (index = 0; i < locations.length; i++)
请注意;
所以,所有循环都应该是
for (index = 0; i < locations.length; i++){
if(i == 0) {
newLoc[i][0] = locations[i][1];
newLoc[i][1] = locations[i][2];
}
else {
if(locations[i][8] == locations[i-1][8]){
newLoc[i-1][0] = (locations[i][1] + locations[i-1][1])/2;
newLoc[i-1][1] = (locations[i][2] + locations[i-2][1])/2;
}
else{
newLoc[i][0] = locations[i][1];
newLoc[i][1] = locations[i][2];
}
}
}
答案 3 :(得分:0)
您正在初始化一维数组,因此,当您遍历循环时,您的javascript代码可能会中断。
尝试使用这种方式进行初始化:
var newLoc = new Array(locations.length).fill(locations.length);
阵列文档:https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Global_Objects/Array