Home > Web Front-end > JS Tutorial > body text

How to output all elements of an array in JavaScript

青灯夜游
Release: 2023-01-07 11:46:45
Original
15039 people have browsed it

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);
Copy after login

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]);
}
Copy after login
var arr = [5,10,20];
for(var key in arr){
console.log(arr[key]);
}
Copy after login

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);
Copy after login

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);
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template