Home > Web Front-end > JS Tutorial > What is the use of javascript map method?

What is the use of javascript map method?

青灯夜游
Release: 2023-01-05 16:09:53
Original
24184 people have browsed it

In JavaScript, the map() method is used to return a new array. The elements in the array are the values ​​of the original array elements after calling the function. The map() method will process the elements in sequence according to the order of the original array elements. Syntax "array.map(function(value, index value, array){})".

What is the use of javascript map method?

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

javascript map() method

map() method returns a new array, and the elements in the array are the values ​​of the original array elements after calling the function.

The map() method processes elements sequentially in the order of the original array elements.

Note: map() will not detect empty arrays. map() does not change the original array.

Grammar:

array.map(function(item,index,arr){})
Copy after login

map is an array method with one parameter, the parameter is a function, and there are 3 parameters in the function

  • ##Parameter 1 :item is required. The value of the current element

  • Parameter 2: index, optional. The index value of the current element in the array

  • Parameter 3: arr is optional. The array object to which the current element belongs

Example:


<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<p>点击按钮获取数组元素的平方根。</p>
<button onclick="myFunction()">点我</button>
<p id="demo"></p>
<script>
var numbers = [4, 9, 16, 25];
function myFunction() {
    x = document.getElementById("demo")
    x.innerHTML = numbers.map(Math.sqrt);
}
</script>
</body>
</html>
Copy after login
Rendering:


What is the use of javascript map method?

[Recommended learning:

javascript advanced tutorial]

The above is the detailed content of What is the use of javascript map method?. 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