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

How to output Array in javascript

醉折花枝作酒筹
醉折花枝作酒筹Original
2021-06-11 11:26:534033browse

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>

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>

3. Use forEach loop to output the array:

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

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

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!

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