[英]How to use a for loop to console log each item of an array?
I'm working on an assignment that experiments with different types of loops. 我正在做一个实验,尝试不同类型的循环。 I have to use a for loop to console.log
each item in the array cars
. 我必须使用for循环来console.log
阵列cars
中的每个项目。 I can only use a for
loop, no other methods such as for each
. 我只能使用for
循环,而不能使用诸如for each
其他方法。 What am I missing? 我想念什么?
I have tried console logging cars
but that logs the entire array a number of times equal to the number of strings in the array, which is obviously not correct. 我已经尝试过控制台记录cars
但是记录整个数组的次数等于数组中字符串的数量,这显然是不正确的。 I'm also fairly certain that the .length
method used in the for
loop is incorrect as well. 我也可以肯定, for
循环中使用的.length
方法也是不正确的。
const cars = ["ford", "chevrolet", "dodge", "mazda", "fiat"]; for (let i = 0; i < cars.length; i++) { console.log(cars) }
cars
refers to the entire array. cars
是指整个阵列。 What you want is to access an item in the array by index in the for loop: that can be done by using cars[i]
: 您想要的是通过for循环中的索引访问数组中的一项:可以通过使用cars[i]
来完成:
const cars = ["ford", "chevrolet", "dodge", "mazda", "fiat"]; for (let i = 0; i < cars.length; i++) { console.log(cars[i]); }
Even better: you an use forEach
instead , which is way more readable: 更好的是:您可以使用forEach
代替 ,这样可读性更高:
const cars = ["ford", "chevrolet", "dodge", "mazda", "fiat"]; cars.forEach(car => { console.log(car); });
You can use foreach too 您也可以使用foreach
const cars = ["ford", "chevrolet", "dodge", "mazda", "fiat"]; cars.forEach(function(element, index) { console.log(element); });
In the above code, you need to log cars[i]
to the console: 在上面的代码中,您需要将cars[i]
登录到控制台:
const cars = ["ford", "chevrolet", "dodge", "mazda", "fiat"]; for (let i = 0; i < cars.length; i++) { console.log(cars[i]) }
cars
is the array, and to access one item in the array, you need to use the numerical index (in this case i
). cars
是数组,要访问数组中的一项,您需要使用数字索引(在本例中为i
)。
You can also eliminate indexes entirely by using a forEach
loop, which is often simpler and faster than a traditional for
loop: 您还可以通过使用forEach
循环来完全消除索引,该循环通常比传统的for
循环更简单,更快捷:
const cars = ["ford", "chevrolet", "dodge", "mazda", "fiat"]; cars.forEach(car => console.log(car));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.