js-Array.from()

例子1——将类数组转换为数组

let array = {
    0: 'name', 
    1: 'age',
    2: 'sex',
    3: ['user1','user2','user3'],
    'length': 4
}
let arr = Array.from(array )
console.log(arr) // ['name','age','sex',['user1','user2','user3']]

如果将上面代码中length属性去掉arr将会是一个长度为0的空数组,如果将代码修改一下,就是具有length属性,但是对象的属性名不再是数字类型的,而是其他字符串型的,代码如下:

let array = {
    'name': 'name', 
    'age': 'age',
    'sex': 'sex',
    'user': ['user1','user2','user3'],
    'length': 4
}
let arr = Array.from(array )
console.log(arr)  // [ undefined, undefined, undefined, undefined ]

 

例子2:——将Set解构的数据转换为数组

let arr = [1,2,3,4,5,6,7,8,9]
let set = new Set(arr)
console.log(Array.from(set))  // [1,2,3,4,5,6,7,8,9]

 

例子3——将字符串转换为数组

let  str = 'hello world!';
console.log(Array.from(str)) // ["h", "e", "l", "l", "o", " ", "w", "o", "r", "l", "d", "!"]

 

求和Sum

function sum() {
     // Array.from()将arguments类数组转换为真数组
     // 也可以使用Array.prototype.slice.call(arguments) , 这是ES5语法, 兼容性更好
     return Array.from(arguments).reduce((prev, cur) => {
         return prev + cur
     }, 0)
 }
 
 console.log(sum(1,2,3,4,5,6)); // 21

 

去重

function unique(array) {
     // 亦可以直接return [...new Set(array)],彻底的ES6语法
     return Array.from(new Set(array))
 }
 
 console.log(unique([1,2,2,3,3,5])); // [1, 2, 3, 5] 

 

数组递增

function range(ends) {
     return Array.from({length: ends}, (_, i) => i + 1)
 }
 
 console.log(range(3)); // [1, 2, 3]

 

利用Array.from() 可以将Unicode编码拆解成数组。

console.log(Array.from('\u6211\u7231\u6572\u4ee3\u7801')) 
 
//(5) ["我", "爱", "敲", "代", "码"]

 

posted on 2020-04-30 11:25  秃了头也不退休  阅读(4563)  评论(0编辑  收藏  举报

导航