【问题标题】:Problem with create list using for loop in Javascript在Javascript中使用for循环创建列表的问题
【发布时间】:2020-03-25 18:29:25
【问题描述】:

我正在尝试创建一个代码来计算我拥有的图像数量,然后创建一个包含图像数量的列表(例如,如果我有 5 张图像,我会得到这个: [0,1,2,3,4]。

我的代码运行,我认为它创建了一个空列表:

这是我的代码(我试图只放相关部分):

//First I filter my image collection according to the number of pixels each image has
//Filter according to number of pixels

var ndviWithCount = withNDVI.map(function(image){
  var countpixels = ee.Number(image.reduceRegion({
  reducer: ee.Reducer.count(),
  geometry: geometry,
  crs: 'EPSG:4326',
  scale: 30,
  }).get('NDVI'));

  return image.set('count', countpixels);
});

print(ndviWithCount, 'ndviWithCount');

//Here I count what is the maximum number of pixels that image has and then I create new collection with //only "big images"

var max = ndviWithCount.reduceColumns(ee.Reducer.max(),  ["count"]);
print(max.get('max'));
var max_pix=max.get('max');

//filter between a range
var filter = ndviWithCount.filter(ee.Filter.rangeContains(
          'count', max_pix, max_pix));
print(filter, 'filtered');
//Here I try to grab the number of images so I can create a list
var num_images=filter.size();

//creating the list of images

var listOfImages =(filter.toList(filter.size()));

//Here is the loop that diesn't work
//I have tried to determine i=0, and then that it will iterate untill i is equal to the number of images
//I try to say, i=0, so add 1 and the nadd it to my list.
for (i = 0; i < num_images; i++) {
  var listOfNumbers=[];
  i=i.add(1);
  listOfNumbers.push(i);

}

我的最终目标是列出包含从 0 或 1 到我拥有的图像数量的 nmbers。

【问题讨论】:

    标签: javascript list for-loop count


    【解决方案1】:

    我找到了解决方案。错误的原因是因为 GEE 环境。 此代码有效:

    var serverList = ee.List.sequence(0,NumberOfImages.subtract(1));
    serverList = serverList.map(function(n) {
      return ee.Number(n).add(1);
    });
    print(serverList);
    

    【讨论】:

      【解决方案2】:
      for (i = 0; i < num_images; i++) {
        var listOfNumbers=[];
        i=i.add(1);
        listOfNumbers.push(i);
      }
      

      您在 for 循环中初始化数组,这不是您想要的。我也不确定 i = i.add(1) 应该是什么。查看for loops上的信息可能会有所帮助。

      let listOfNumbers = [];
      for (let i = 0; i < num_images; i++) {
            listOfNumbers.push(i);
      }
      

      【讨论】:

      • with i+1 我试图做一些类似于我知道在 python 中做的事情,即 fount for 循环,所以每当 i 等于我定义的数字时(比如最大值) 它将停止 for 循环。
      • 所有这些都在顶级语句中处理:让 i = 0; i
      • 当我使用您的代码时,我收到错误消息 SyntaxError: Unexpected token (4:4)。我试图创建这样的列表也没有我的代码并得到同样的错误
      • 您对词法范围有疑问(例如,您已经在某处声明了“listOfNumbers”)。这是一个在线工作 REPL 显示 for 循环。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-03-26
      • 2021-12-25
      • 1970-01-01
      • 2017-03-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多