from()
方法从任何类数组对象或 可迭代 对象创建一个新 数组。
示例
// creating a new array from string
let newArray = Array.from("abc");
console.log(newArray);
// Output:
// [ 'a', 'b', 'c' ]
from() 语法
from()
方法的语法是
Array.from(arraylike, mapFunc, thisArg)
from()
方法作为一个静态方法,通过 Array
类名调用。
from() 参数
from()
方法可以接受 三个 参数
- arraylike - 要转换为数组的类数组对象或可迭代对象。
- mapFunc (可选) - 映射函数,将对每个元素进行调用。
- thisArg (可选) - 执行 mapFunc 时用作 this 的值。
注意:Array.from(obj, mapFunc, thisArg)
等同于 Array.from(obj).map(mapFunc, thisArg)
。
from() 返回值
- 返回一个新的
Array
实例。
示例 1:使用类数组对象的 from() 方法
// creating an array from a string
let array1= Array.from("JavaScript");
console.log(array1);
输出
['J', 'a', 'v', 'a', 'S', 'c', 'r', 'i', 'p', 't']
在上面的示例中,我们使用 from()
方法从 'JavaScript'
字符串创建了一个新数组。
我们通过 Array
类调用了该方法,即 Array.from("JavaScript")
。该方法返回一个新数组 ['J', 'a', 'v', 'a', 'S', 'c', 'r', 'i', 'p', 't']
并将其赋给 array1。
示例 2:带有映射函数的 from() 方法
// function that returns a new array
function createArray(arraylike, mapFunc) {
return Array.from(arraylike, mapFunc);
}
// using arrow function for mapFunc
let result = createArray([2, 4, 6], (element) => element + 2);
console.log(result);
输出
[ 4, 6, 8 ]
在上面的示例中,我们在 from()
方法中传递了一个映射函数,该函数将创建的数组的每个元素增加 2。
示例 2:使用 Set 的 from() 方法
// defining a Set
let set = new Set(["JavaScript", "Python", "Go", "Python"]);
// creating an array from the given set
let result = Array.from(set);
console.log(result);
输出
[ 'JavaScript', 'Python', 'Go' ]
在这里,我们使用可迭代对象 Set
和 from()
方法创建了一个新数组。
另请阅读