ES6 - generate an array of numbers

前端 未结 6 717
我寻月下人不归
我寻月下人不归 2021-01-31 08:03

Having googled for it I found two solutions:

6条回答
  •  日久生厌
    2021-01-31 08:39

    A tour of Array.from thru practical examples

    Array.from also accepts a second argument which is used as a mapping function

    let out = Array.from(Array(10), (_,x) => x);
    console.log(out);
    // [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

    This is nice to know because you might want to generate arrays that are sometimes more complex than just 0 thru N.

    const sq = x => x * x;
    let out = Array.from(Array(10), (_,x) => sq(x));
    console.log(out);
    // [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

    Or you can make arrays out of generators, too

    function* range(start, end, step) {
      while (start < end) {
        yield start;
        start += step;
      }
    }
    
    let out = Array.from(range(10,20,2));
    
    console.log(out); // [10, 12, 14, 16, 18]

    Array.from is just massively powerful. People don't even realize its full potential yet.

    const ord = x => x.charCodeAt(0);
    const dec2hex = x => `0${x.toString(16)}`.substr(-2);
    
    // common noob code
    {
      let input = "hello world";
      let output = input.split('').map(x => dec2hex(ord(x)));
      
      console.log(output);
      // ["68", "65", "6c", "6c", "6f", "20", "77", "6f", "72", "6c", "64"]
    }
    
    // Array.from
    {
      let input = "hello world";
      let output = Array.from(input, x => dec2hex(ord(x)));
      
      console.log(output);
      // ["68", "65", "6c", "6c", "6f", "20", "77", "6f", "72", "6c", "64"]
    }

提交回复
热议问题