Home  >  Article  >  Web Front-end  >  How to output all elements of an array in JavaScript

How to output all elements of an array in JavaScript

青灯夜游
青灯夜游Original
2021-09-02 15:32:0815031browse

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.

How to output all elements of an array in JavaScript

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);

How to output all elements of an array in JavaScript

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]);
}

How to output all elements of an array in JavaScript

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);

How to output all elements of an array in JavaScript

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);

How to output all elements of an array in JavaScript

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn