Home > Web Front-end > JS Tutorial > How to output Array in javascript

How to output Array in javascript

醉折花枝作酒筹
Release: 2023-01-06 11:17:19
Original
4087 people have browsed it

Javascript's Array output methods are: 1. Use the "for in" method to loop the array; 2. Use the for loop to output the array; 3. Use forEach to loop the array; 4. Use the for-of loop to output the array. .

How to output Array in javascript

The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.

In JavaScript, you can traverse the array through a loop, and use the document.writeln() or console.log() method to output the array in the loop.

Example of output array in javascript:

1. Use the for in method to loop the output array:

<script language="javascript" type="text/javascript">
var str = "how are you today";
var arr = str.split(" ");
for(var key in arr){
 document.writeln(arr[key]);
}
</script>
Copy after login

2. Use the for loop to output the array:

<script language="javascript" type="text/javascript">
var str = "how are you today";
var arr = str.split(" ");
for(var i=0;i<arr.length;i++){
 document.writeln(arr[i]);
}
</script>
Copy after login

3. Use forEach loop to output the array:

var arr = [1, 2, 3, 4];
arr.forEach(function(val, index) {
    console.log(val, index);
});
Copy after login

4. Use for-of loop to output the array:

for-of is a new traversal array or array-like function in ES6 method. It appears mainly to solve the defects of the three traversal methods in ES5:

forEach cannot break or return

let arr=[3,7,9];
     for (let key of arr){
             console.log(key);
    }
Copy after login

JavaScript array:

Array objects are used in separate A series of values ​​is stored in a variable name.

[Recommended learning: javascript advanced tutorial]

The above is the detailed content of How to output 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