Array.from()方法详解
Array.from()是JavaScript中一个非常有用的方法,它可以将类似数组或可迭代对象(iterable)转换为真正的数组。这个方法在处理一些特殊的数据结构或需要对数据进行操作时非常方便。
一、Array.from()的语法
-
arrayLike:一个类似数组或可迭代对象,需要转换为数组的内容。
-
mapFn(可选):对每个元素进行处理的回调函数。
-
thisArg(可选):执行回调函数时的this值。
Array.from(arrayLike[, mapFn[, thisArg]])
二、示例
1、将字符串转换为数组
const str = "Hello, World!";
const arr = Array.from(str);
console.log(arr); // ["H", "e", "l", "l", "o", ",", " ", "W", "o", "r", "l", "d", "!"]
2、将类似数组的对象转换为数组
const obj = {0: "a", 1: "b", 2: "c", length: 3};//实际上是一个类似数组的对象
const arr = Array.from(obj);
console.log(arr); // ["a", "b", "c"]//将这个类似数组的对象转换为一个真正的数组
3、使用mapFn处理每个元素
const arr = [1, 2, 3];
const doubleArr = Array.from(arr, num => num * 2);//我们使用Array.from()的第二个参数mapFn来对原始数组中的每个元素进行处理,并返回一个新的数组。在这个例子中,我们将每个元素乘以2,得到一个新的数组doubleArr。
console.log(doubleArr); // [2, 4, 6]