Detailed explanation of array.form()

Array.from()Is a static method in JavaScript, used to convert array-like objects or iterable objects (such as Set, Map, etc.) into a new array.

Its syntax is as follows:

 
  

javascriptCopy code

Array.from(iterable[, mapFn[, thisArg]])

Parameter explanation:

  • iterable: Iterable object to be converted to an array.
  • mapFn (Optional): Callback function to map each element.
  • thisArg (optional):  this The value in the callback function.

Example 1: Convert string to array

 
  

javascriptCopy code

const str = 'hello'; const arr = Array.from(str); console.log(arr); // ['h', 'e', 'l', 'l', 'o']

Example 2: Convert iterable object to array and perform mapping operation

 
  

javascriptCopy code

const set = new Set([1, 2, 3]); const arr = Array.from(set, item => item * 2); console.log(arr); // [2, 4, 6]

Therefore, Array.from()iterable objects can be easily converted into arrays, and elements can be mapped during the conversion process.

Guess you like

Origin blog.csdn.net/kuang_nu/article/details/133203290