Array from a string

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

Array from a set

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

Array from a map

  1. const map = new Map([[1, 2], [2, 4], [4, 8]]);
  2. Array.from(map);
  3. // [[1, 2], [2, 4], [4, 8]]
  4. const mapper = new Map([['1', 'a'], ['2', 'b']]);
  5. Array.from(mapper.values());
  6. // ['a', 'b'];
  7. Array.from(mapper.keys());
  8. // ['1', '2'];

Array from an Array-like obj(类数组对象)

  1. function f() {
  2. return Array.from(arguments);
  3. }
  4. f(1, 2, 3);
  5. // [ 1, 2, 3 ]

Using arrow functions and Array.from()

  1. // Using an arrow function as the map function to
  2. // manipulate the elements
  3. Array.from([1, 2, 3], x => x + x);
  4. // [2, 4, 6]
  5. // Generate a sequence of numbers
  6. // Since the array is initialized with `undefined` on each position,
  7. // the value of `v` below will be `undefined`
  8. Array.from({length: 5}, (v, i) => i);
  9. // [0, 1, 2, 3, 4]

使用对象填充数组

  1. const length = 3;
  2. const resultA = Array.from({ length }, () => ({}));
  3. const resultB = Array(length).fill({});
  4. resultA; // => [{}, {}, {}]
  5. resultB; // => [{}, {}, {}]
  6. resultA[0] === resultA[1]; // => false
  7. resultB[0] === resultB[1]; // => true

克隆一个数组

  1. const numbers = [3, 6, 9];
  2. const numbersCopy = Array.from(numbers);
  3. numbers === numbersCopy; // => false