定义:
将类数组对象、具有可迭代接口的数据转化为真正的数组。
- 类数组对象:指的是必须要有length属性。
// 1.对象里面存在length属性:
// 对象属性名为数字或者数字字符串,转化的为对象属性值的数组,
// 否则转出的是长度为length的数组,每一项的值都是undefined。
const obj = {
1: 'name',
'3': 'ccc',
length: 5
}
// [undefined, 'name', undefined, 'ccc', undefined]
Array.from(obj)
// 2.没有length属性,转出来的是空数组。
// []
Array.from({ 1: 'name', '2': 'ccc' })
- 具有可迭代接口的数据转为数组,比如Set,Map,Array,类数组对象 arguments。
Array.from()还可以接受第二个参数
let arr = [1,2,3]
let set = new Set(arr)
let arr1 = Array.from(set, (item) => { return item + 1})
//[2, 3, 4]
console.log(arr1)
将字符串转化为数组
let str = 'james'
//["j", "a", "m", "e", "s"]
console.log(Array.from(str))