繁体   English   中英

用值填充数组,但是当我用console.log()检查数组时,数组值显示为未定义

[英]Filling array with values but when I check my array with console.log() my array values come up as undefined

 var myArray = []; //Create an empty array //Fills empty array with values for (i = 0; i < myArray.length - 1; i++) { myArray[i] = i * i; //Each index is equal to the square of the index number 0=0, 1=1, 2=4, etc. } console.log(myArray.length); console.log(myArray[0]); 

console.log(myArray.length); 在控制台中返回0

console.log(myArray[0]); 在控制台中返回未定义

myArray.length返回数组myArray的元素数。

当数组到达循环时,其中没有任何元素( [] )。 因此,当您执行myArray.length您将获得数字0作为回报。

因此,您的for循环将运行零次,因为0 < 0永远不会为真(并且要使其运行,中间条件需要评估为true),这意味着当您到达console.log ,数组中将不会设置任何内容,并且因此myArray[0]将是未定义的。

因此,要生成值,您需要在for循环中使用大于零的数字。 在下面的示例中,我创建了一个包含10元素的数组:

 var myArray = []; //Create an empty array //Fills empty array with values for (i = 0; i < 10; i++) { // <--- Change to i < 10 here to run 10 times (for i ranging within [0, 10) (0 <= i < 10) myArray[i] = i * i; //Each index is equal to the square of the index number 0=0, 1=1, 2=4, etc. } console.log(myArray.length); // 10 console.log(myArray[0]); // 0 console.log(myArray[1]); // 1 console.log(myArray[2]); // 4 

启动循环时, myArray.length为零。 因此,它甚至都没有进入循环,因此数组在您初始化时仍然保留。

您可以简单地使用Array.from并使用mapFn作为第二个参数来生成数字:

 const generate = n => Array.from({length: n}, (x,i) => i*i) console.log(generate(5)) console.log(generate(10)) 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM