ES6 Array.from方法用法总结

来源:互联网 发布:java获取进程端口号 编辑:程序博客网 时间:2024/06/08 05:48

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

[javascript] view plain copy
print?
  1. let arrayLike = {  
  2. ’0’‘a’,  
  3. ’1’‘b’,  
  4. ’2’‘c’,  
  5. length: 3  
  6. };  
  7. // ES5 的写法  
  8. var arr1 = [].slice.call(arrayLike); // [‘a’, ‘b’, ‘c’]  
  9. // ES6 的写法  
  10. let arr2 = Array.from(arrayLike); // [‘a’, ‘b’, ‘c’]  
  11.   
  12. // NodeList 对象  
  13. let ps = document.querySelectorAll(’p’);  
  14. Array.from(ps).forEach(function (p) {  
  15. console.log(p);  
  16. });  
  17. // arguments 对象  
  18. function foo() {  
  19. var args = Array.from(arguments);  
  20. // …  
  21. }  
  22.   
  23. Array.from(’hello’)  
  24. // [‘h’, ‘e’, ‘l’, ‘l’, ‘o’]  
  25. let namesSet = new Set([‘a’‘b’])  
  26. Array.from(namesSet) // [‘a’, ‘b’]  
  27.   
  28. Array.from({ length: 3 });  
  29. // [ 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?
  1. Array.from(arrayLike, x => x * x);  
  2. //  等同于  
  3. Array.from(arrayLike).map(x => x * x);  
  4. Array.from([1, 2, 3], (x) => x * x)  
  5. // [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?
  1. // arguments 对象  
  2. function foo() {  
  3. var args = […arguments];  
  4. }  
  5. // NodeList 对象  
  6. […document.querySelectorAll(’div’)]  
// arguments 对象function foo() {var args = [...arguments];}// NodeList 对象[...document.querySelectorAll('div')]



原创粉丝点击