Javascript数组未定义大小

Sce*_*T1c -6 javascript arrays

我正在尝试使用while循环填充数组.当我尝试读取某个索引处的数据时,它一直给我未定义但数组的长度告诉我必须添加一些东西.

  var test = [];
  while (i < 16)
  {
    test[i] = i;
    i++;
    console.log(test.length);
    console.log(test[i]);
  }
Run Code Online (Sandbox Code Playgroud)

控制台输出:

1
Fibbo.html:48 undefined
Fibbo.html:47 2
Fibbo.html:48 undefined
Fibbo.html:47 3
Fibbo.html:48 undefined
Fibbo.html:47 4
Fibbo.html:48 undefined
Fibbo.html:47 5
Fibbo.html:48 undefined
Fibbo.html:47 6
Fibbo.html:48 undefined
Fibbo.html:47 7
Fibbo.html:48 undefined
Fibbo.html:47 8
Fibbo.html:48 undefined
Fibbo.html:47 9
Fibbo.html:48 undefined
Fibbo.html:47 10
Fibbo.html:48 undefined
Fibbo.html:47 11
Fibbo.html:48 undefined
Fibbo.html:47 12
Fibbo.html:48 undefined
Fibbo.html:47 13
Fibbo.html:48 undefined
Fibbo.html:47 14
Fibbo.html:48 undefined
Fibbo.html:47 15
Fibbo.html:48 undefined
Fibbo.html:47 16
Fibbo.html:48 undefined
Run Code Online (Sandbox Code Playgroud)

Shr*_*yas 6

您正在i处插入并检查i + 1处的值.这应该修复您的代码 -

  var i = 0;
  var test = [];
  while (i < 16)
  {
    test[i] = i;
    console.log(test.length);
    console.log(test[i]);
    i++;
  }
Run Code Online (Sandbox Code Playgroud)

  • 你不需要_initialize_`i`为**0**吗? (3认同)