Home >Web Front-end >JS Tutorial >How to output all elements of an array in JavaScript
Methods for JavaScript to output arrays: 1. Use "console.log(array name)" to output the array; 2. Use the for or for in statement to loop through the array; 3. Use forEach() to traverse the array and output the array. Elements; 4. Use map() to traverse the array and output the array elements.
The operating environment of this tutorial: Windows 7 system, JavaScript version 1.8.5, Dell G3 computer.
Method 1: Use console.log(array name) directly
var a = [5,10,20]; console.log(a);
Method 2: Use for/for in loop output array
var arr = [5,10,20]; for(var i=0;i<arr.length;i++){ console.log(arr[i]); }
var arr = [5,10,20]; for(var key in arr){ console.log(arr[key]); }
Method 3: forEach() traverses the array and loops the output array
var arr = [5,10,20]; function f(value) { console.log(value); } arr.forEach(f);
Method 4: map() method traverses the array and loops to output the array
var arr = [5,10,20]; function f(value) { return value; } var a=arr.map(f); console.log(a);
The above is the detailed content of How to output all elements of an array in JavaScript. For more information, please follow other related articles on the PHP Chinese website!