javascript - Create Simple Dynamic Array

前端 未结 16 1981
刺人心
刺人心 2020-12-14 06:53

What\'s the most efficient way to create this simple array dynamically.

var arr = [ \"1\", \"2\", \"3\", \"4\", \"5\", \"6\", \"7\", \"8\", \"9\", \"10\"];
<         


        
16条回答
  •  春和景丽
    2020-12-14 07:04

    With ES2015, this can be achieved concisely in a single expression using the Array.from method like so:

    Array.from({ length: 10 }, (_, idx) => `${++idx}`)
    

    The first argument to from is an array like object that provides a length property. The second argument is a map function that allows us to replace the default undefined values with their adjusted index values as you requested. Checkout the specification here

提交回复
热议问题