delphi - for循环中的变量没有被调用

标签 delphi variables for-loop

我正在使用 DBXJson 解析一个名为 response.json 的简单 json 文件,并在网格中显示其内容,但只有网格的第一行填充了数据,即使有是要显示更多行/数据。我在下面的代码中使用了自定义网格,但我尝试了使用标准字符串网格的下面代码的变体,它表现出了相同的行为。这是我用来解析响应并将其显示在网格中的代码。

var
  sl: TStringList;
  LJsonArr: TJSONArray;
  LJsonValue: TJSONValue;
  LItem: TJSONValue;
  col, row: Integer;
begin
  col := 0;
  row := 0;

  sl := TStringList.Create;
  sl.LoadFromFile('response.txt');
  LJsonArr := TJSONObject.ParseJSONValue(TEncoding.UTF8.GetBytes(sl.text), 0)
    as TJSONArray;

  for LJsonValue in LJsonArr do
  begin
    NextGrid1.AddRow();

    for LItem in TJSONArray(LJsonValue) do
    begin
      NextGrid1.Cells[col, row] := TJSONPair(LItem).JsonValue.Value;
      inc(col);
    end;
    inc(row);
  end;
  sl.Free;
end;

我怀疑问题在于 row 变量不合适并且没有被调用,这导致只显示第一行,但我可能会弄错,我我希望有一双新的眼睛能够发现问题。

最佳答案

问题是每次开始新行时,col 都必须重新初始化为零。因此将 col 的初始化移到外循环中。

row := 0;
for LJsonValue in LJsonArr do
begin
  col := 0;
  NextGrid1.AddRow();
  for LItem in TJSONArray(LJsonValue) do
  begin
    NextGrid1.Cells[col,row] := TJSONPair(LItem).JsonValue.Value;
    inc(col);
  end;
  inc(row);
end;

我不知道这个 JSON 库,但如果它允许您通过随机访问来访问数组元素,那么传统的 oindexed for 循环将导致比您使用的 for in 循环更干净的代码。在伪代码中:

for row := 0 to arr.length do
begin
  item := arr[row];
  for col := 0 to item.length do
    grid.Cells[col,row] := item[col];
end;

根据经验,如果您不需要知道项目索引,则 for in 循环会更好。然而,一旦您需要知道项目索引,那么传统的索引 for 循环通常是首选。

关于delphi - for循环中的变量没有被调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25459098/

相关文章:

c# - 在 switch 语句外使用变量 + asp.net mvc

德尔福2009 : Is there a keyboard shortcut for searching the Structure panel?

c++ - 代码从 C/C++ 转换为 Delphi

ios - XE8.1 : file was built for archive which is not the architecture being linked (arm64)

c# - 我可以声明一个在一行中使用并在行后立即丢弃的变量吗?

php - Perl 有类似于 PHP 的 constant() 的东西吗?

python - 在 Python for 循环中跳过可变次数的迭代

jQuery for 循环动态值

python - 某些列的唯一值,DF pandas

delphi - 我自己的存储和检索使用 Delphi 文本 DFM 格式的生命周期很长