ES6-数组中的from()方法

定义

该方法用于将两类对象转换成真正的数组:类似数组的对象 和 可遍历对象;

语法

Array.from( arrayLike, mapFun, thisArg );

参数

  • arrayLike:必需。想要转换成数组的伪数组对象或可迭代对象;
  • mapFun:可选。如果指定了该参数,新数组中的每个元素会执行该回调函数。
  • thisArg:可选。执行回调函数mapFun时this对象。

返回值

一个新的数组实例

使用(例子)

从 String 生成数组
Array.from('foo'); 
// [ "f", "o", "o" ]
从 Set 生成数组
const set = new Set(['foo', 'bar', 'baz', 'foo']);
Array.from(set);
// [ "foo", "bar", "baz" ]
从 Map 生成数组
const map = new Map([[1, 2], [2, 4], [4, 8]]);
Array.from(map);
// [[1, 2], [2, 4], [4, 8]]

const mapper = new Map([['1', 'a'], ['2', 'b']]);
Array.from(mapper.values());
// ['a', 'b'];

Array.from(mapper.keys());
// ['1', '2'];
从类数组对象(arguments)生成数组
function f() {
    
    
  return Array.from(arguments);
}

f(1, 2, 3);

// [ 1, 2, 3 ]
在 Array.from 中使用箭头函数
// Using an arrow function as the map function to
// manipulate the elements
Array.from([1, 2, 3], x => x + x);
// [2, 4, 6]


// Generate a sequence of numbers
// Since the array is initialized with `undefined` on each position,
// the value of `v` below will be `undefined`
Array.from({
    
    length: 5}, (v, i) => i);
// [0, 1, 2, 3, 4]
Sequence generator (range)
// Sequence generator function (commonly referred to as "range", e.g. Clojure, PHP etc)
const range = (start, stop, step) => Array.from({
    
     length: (stop - start) / step + 1}, (_, i) => start + (i * step));

// Generate numbers range 0..4
range(0, 4, 1);
// [0, 1, 2, 3, 4] 

// Generate numbers range 1..10 with step of 2 
range(1, 10, 2); 
// [1, 3, 5, 7, 9]

// Generate the alphabet using Array.from making use of it being ordered as a sequence
range('A'.charCodeAt(0), 'Z'.charCodeAt(0), 1).map(x => String.fromCharCode(x));
// ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"]
数组去重合并
function combine(){
    
     
    let arr = [].concat.apply([], arguments);  //没有去重复的新数组 
    return Array.from(new Set(arr));
} 

var m = [1, 2, 2], n = [2,3,3]; 
console.log(combine(m,n));                     // [1, 2, 3]

注意

*IE浏览器不支持此方法

猜你喜欢

转载自blog.csdn.net/qq_40117020/article/details/108306470
今日推荐