array.from用法
时间: 2023-10-08 18:12:51 浏览: 50
`Array.from()` 是 JavaScript 中的一个静态方法,它可以将类数组对象或可迭代对象转换为一个新的数组。它接受两个参数:第一个参数是要转换成数组的对象,第二个参数(可选)是一个映射函数,用于对数组中的每个元素进行转换。
以下是 `Array.from()` 的使用示例:
```javascript
// 转换字符串为数组
const str = 'hello';
const arr = Array.from(str);
console.log(arr); // ['h', 'e', 'l', 'l', 'o']
// 转换 Set 对象为数组
const set = new Set([1, 2, 3]);
const arr2 = Array.from(set);
console.log(arr2); // [1, 2, 3]
// 使用映射函数转换数组
const arr3 = [1, 2, 3];
const mappedArr = Array.from(arr3, x => x * 2);
console.log(mappedArr); // [2, 4, 6]
```
注意:`Array.from()` 方法在 ES6 中被引入,因此在使用它之前,你需要检查你的浏览器是否支持它,或者使用 polyfill 来提供支持。
相关问题
Array.from用法
Array.from是一个静态方法,它用于从类似数组或可迭代对象中创建一个新的数组实例。它接受一个类数组对象或可迭代对象作为第一个参数,并可选地接受一个映射函数作为第二个参数。
例如,我们可以使用Array.from将字符串转换为字符数组:
```javascript
const str = 'hello';
const arr = Array.from(str);
console.log(arr); // ['h', 'e', 'l', 'l', 'o']
```
我们还可以将类似数组的对象(如NodeList)转换为真正的数组:
```javascript
const nodeList = document.querySelectorAll('div');
const arr = Array.from(nodeList);
console.log(arr); // [div, div, div, ...]
```
另外,我们还可以使用Array.from配合映射函数来对数组进行转换或处理:
```javascript
const arr = [1, 2, 3, 4];
const transformedArr = Array.from(arr, item => item * 2);
console.log(transformedArr); // [2, 4, 6, 8]
```
在上面的示例中,我们将原始数组中的每个元素乘以2,并将结果存储在新的数组中。
总而言之,Array.from是一个非常有用的方法,它可以帮助我们从不同类型的对象创建新的数组,并且可以通过映射函数对数组进行转换或处理。
Array.from使用方法
Array.from() 方法从一个类似数组或可迭代对象中创建一个新的数组实例。它的语法如下:
```javascript
Array.from(arrayLike[, mapFn[, thisArg]])
```
参数解释:
- `arrayLike`:类似数组或可迭代对象。
- `mapFn` (可选):一个类似于 `Array.prototype.map()` 的回调函数,用来对每个元素进行处理,将处理后的结果放入新数组中。
- `thisArg` (可选):执行 `mapFn` 时 `this` 对象的值。
调用示例:
```javascript
// 从一个字符串中创建一个新的数组
Array.from('hello') // ['h', 'e', 'l', 'l', 'o']
// 从一个 Set 对象中创建一个新的数组
const set = new Set(['foo', 'bar', 'baz'])
Array.from(set) // ['foo', 'bar', 'baz']
// 使用 mapFn 将每个元素加倍
Array.from([1, 2, 3], x => x * 2) // [2, 4, 6]
```
需要注意的是,`Array.from()` 方法只能将类似数组或可迭代对象转换成数组,如果传入的参数不满足该条件,将会抛出 `TypeError` 异常。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)