Array.from():

Array.from() 方法从一个类似数组或可迭代对象创建一个新的,浅拷贝的数组实例。

语法

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

参数

arrayLike

想要转换成数组的伪数组对象或可迭代对象。

mapFn 可选

如果指定了该参数,新数组中的每个元素会执行该回调函数。

thisArg 可选

可选参数,执行回调函数 mapFn 时 this 对象。

返回值

一个新的s数组实例。

例子

1.用字符串生成数组

console.log(Array.from('foo'));
// expected output: Array ["f", "o", "o"]

2.在 Array.from 中使用箭头函数

console.log(Array.from([1, 2, 3], x => x + x));
// expected output: Array [2, 4, 6]

3.将对象转换数组

请注意:1.object中必须有length属性,返回的数组长度取决于length长度

               2.key必须是数值

let obj = {
        0: 'hellow world',
        1: 'xiaoming',
        2: 'xiaohong',
        'length': 3
    } 
let arr = Array.from(obj)
console.log(arr);
// expected output: Array  (3) ['hellow world', 'xiaoming', 'xiaohong']

 

Logo

基于 Vue 的企业级 UI 组件库和中后台系统解决方案,为数万开发者服务。

更多推荐