Home  >  Article  >  Web Front-end  >  How to modify each element of es6 array

How to modify each element of es6 array

青灯夜游
青灯夜游Original
2022-05-05 15:34:382759browse

Two methods: 1. Use forEach() to pass each element into the callback function for modification. The syntax "arr.forEach(function f(v){//modify v and output }". 2. Use map() to pass each element into the callback function for modification, and finally output the processed array.

How to modify each element of es6 array

The operating environment of this tutorial: Windows 7 system, ECMAScript version 6, Dell G3 computer.

In es6, you can use the following two methods to modify each element of the array

  • forEach(): Execute the callback function once for each element of the array.

  • map(): Process each element of the array through the specified function and return the processed array.

1. Use the forEach() function

The forEach() method is used to call each element of the array and pass the element to the callback function.

Example: Add 1 to each element of the array

var arr = [4, 9, 16, 25];
console.log("原数组:"+arr);
arr.forEach(function myFunction(item) {
	console.log("新数组:"+(item+1));
});

How to modify each element of es6 array

2. Use the map() function

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

Example: Add 3 to each element of the array

var arr = [4, 9, 16, 25];
console.log("原数组:"+arr);
var a1=arr.map(function myFunction(item) {
	 return item+3;
});
console.log("新数组:"+a1);

How to modify each element of es6 array

【Related recommendations: javascript video tutorial, web front-end

The above is the detailed content of How to modify each element of es6 array. 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