您的位置:首页 > Web前端 > JavaScript

ES6 Array.from方法用法总结

2017-06-23 21:43 351 查看
Array.from方法用于将两类对象转为真正的数组:类似数组的对象( array-like object )和可遍历( iterable )的对象(包括 ES6 新增的数据结构 Set 和Map )。

[javascript] view plain copy print?let arrayLike = {
’0’: ‘a’,
’1’: ‘b’,
’2’: ‘c’,
length: 3
};
// ES5 的写法
var arr1 = [].slice.call(arrayLike); // [‘a’, ‘b’, ‘c’]
// ES6 的写法
let arr2 = Array.from(arrayLike); // [‘a’, ‘b’, ‘c’]

// NodeList 对象
let ps = document.querySelectorAll(’p’);
Array.from(ps).forEach(function (p) {
console.log(p);
});
// arguments 对象
function foo() {
var args = Array.from(arguments);
// …
}

Array.from(’hello’)
// [‘h’, ‘e’, ‘l’, ‘l’, ‘o’]
let namesSet = new Set([‘a’, ‘b’])
Array.from(namesSet) // [‘a’, ‘b’]

Array.from({ length: 3 });
// [ undefined, undefined, undefined ]
let arrayLike = {
'0': 'a',
'1': 'b',
'2': 'c',
length: 3
};
// ES5 的写法
var arr1 = [].slice.call(arrayLike); // ['a', 'b', 'c']
// ES6 的写法
let arr2 = Array.from(arrayLike); // ['a', 'b', 'c']

// NodeList 对象
let ps = document.querySelectorAll('p');
Array.from(ps).forEach(function (p) {
console.log(p);
});
// arguments 对象
function foo() {
var args = Array.from(arguments);
// ...
}

Array.from('hello')
// ['h', 'e', 'l', 'l', 'o']
let namesSet = new Set(['a', 'b'])
Array.from(namesSet) // ['a', 'b']

Array.from({ length: 3 });
// [ undefined, undefined, undefined ]


Array.from还可以接受第二个参数,作用类似于数组的map方法,用来对每个元素进行处理,将处理后的值放入返回的数组。

[javascript] view plain copy print?Array.from(arrayLike, x => x * x); // 等同于 Array.from(arrayLike).map(x => x * x); Array.from([1, 2, 3], (x) => x * x) // [1, 4, 9]
Array.from(arrayLike, x => x * x);
//  等同于
Array.from(arrayLike).map(x => x * x);
Array.from([1, 2, 3], (x) => x * x)
// [1, 4, 9]


值得提醒的是,扩展运算符(…)也可以将某些数据结构转为数组。

[javascript] view plain copy print?// arguments 对象
function foo() {
var args = […arguments];
}
// NodeList 对象
[…document.querySelectorAll(’div’)]
// arguments 对象
function foo() {
var args = [...arguments];
}
// NodeList 对象
[...document.querySelectorAll('div')]
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  javascript es6