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.
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)); });
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);
【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!