Get the App
SLTechnology News&Howtos  ›  Development  › 

How the es6 array modifies each element

Shulou Source: shulou.com Published: 2022-05-31 18:11:52 11月12日 Update

Most people don't understand the knowledge points of this article "how to modify each element of es6 array", so Xiaobian summarizes the following contents for everyone. The contents are detailed, the steps are clear, and they have certain reference value. I hope everyone can gain something after reading this article. Let's take a look at this article "how to modify each element of es6 array".

Two methods: 1. Use forEach() to pass each element into the callback function for modification, 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.

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

In es6, you can modify each element of an array in two ways

forEach(): Each element of the array executes a callback function once.

map(): Process each element of an array by specifying a function and return the processed array.

1. Use forEach() function

The forEach() method calls each element of the array and passes the element to the callback function.

Example: Add 1 to each element of an array

var arr = [4, 9, 16, 25];console.log("original array: "+arr);arr.forEach(function myFunction(item) { console.log("new array: "+(item+1));});

2. Use map() function

The map() method returns a new array whose elements are the processed values of the original array elements.

Example: Add 3 to each element of an array

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

The above is the content of this article about "how to modify each element of es6 array". I believe everyone has a certain understanding. I hope the content shared by Xiaobian will help everyone. If you want to know more relevant knowledge, please pay attention to the industry information channel.

Tags: Array element function content method processing article knowledge example article output original value can make most of it that is tutorials more steps environment Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno NVidia Microsoft Xiaomi Shulou Information MySQL