Abo

容易忽略的 Array.from()

容易遗忘的Array跟Map的语法

hello


        

从 string 生成数组

1
2
Array.from('foo'); 
// [ "f", "o", "o" ]

从set生成数组

1
2
3
const set = new Set(['foo', 'bar', 'baz', 'foo']);
Array.from(set);
// [ "foo", "bar", "baz" ]

从map生成数组

1
2
3
4
5
6
7
8
9
10
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)生成数组

1
2
3
4
5
6
7
function f() {
return Array.from(arguments);
}

f(1, 2, 3);

// [ 1, 2, 3 ]

在 Array.from 中使用箭头函数

1
2
3
4
5
6
7
8
9
10
11
// 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]

数组去重合并

1
2
3
4
5
6
7
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]