简体   繁体   English

如果我想使用 forEach 循环显示数组中的前 5 个元素怎么办?

[英]What to do if i want to show the first 5 elements from the array by using forEach loop?

There are 10 elements in an array.数组中有 10 个元素。 What to do if i want to show the first 5 elements from the array by using forEach loop?如果我想使用 forEach 循环显示数组中的前 5 个元素怎么办?

let arrays =[1, 2, 4, 6, 7, 44, 5, 7, 6]
 arrays.forEach(array =>{}) //

To show the first 5 elements from the array by using forEach loop, you can use if statement要使用 forEach 循环显示数组中的前 5 个元素,可以使用 if 语句

const arrays = [1, 2, 4, 6, 7, 44, 5, 7, 6];

arrays.forEach(function(value, index, array) {

    if(index <= 4) {
        document.write(value + "<br>");
    }

});

Where parameters:其中参数:

  • Index = The index of the current element. Index = 当前元素的索引。
  • Value = The value of the current element.值 = 当前元素的值。
  • Array = The array of the current element. Array = 当前元素的数组。

https://www.w3schools.com/jsref/jsref_foreach.asp https://www.w3schools.com/js/js_if_else.asp https://www.w3schools.com/jsref/jsref_foreach.asp https://www.w3schools.com/js/js_if_else.asp

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

相关问题 如何从数组中删除所需的对象,然后使用.forEach将它们添加到另一个数组中? - How do I remove the objects I want from an array and add them to another array using .forEach? 如何使用 forEach 循环在 IIFE 中调用数组? - How do I call an array within an IIFE using a forEach loop? 如何从Angular中的foreach循环返回数组数据 - How do I return array data from a foreach loop in Angular 如何通过在 forEach 循环中使用键返回我想要的对象? - How do I return the object I want by using a key in a forEach loop? 如何使用for循环交换数组的前2个元素 - how to swap the first 2 elements of an array using a for loop 如何使用 for 循环将 javascript 数组的元素打印到网页? - How do I print the elements of a javascript array to the webpage using a for loop? 如何使用 for of loop javascript 返回数组中的元素数? - How do I return the number of elements in an array using for of loop javascript? 如何使用javascript中的for循环成对检索数组元素? - How do I retrieve array elements in pairs using the for loop in javascript? 使用forEach循环将数据保存在MongoDB中以存储数组中的元素 - Using forEach loop to save data in a MongoDB for elements in an array 如何在forEach循环/函数中删除空元素? - Where do I remove null elements in a forEach-loop/function?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM