How to create an array containing 1…N

后端 未结 30 1506
旧时难觅i
旧时难觅i 2020-11-22 01:04

I\'m looking for any alternatives to the below for creating a JavaScript array containing 1 through to N where N is only known at runt

30条回答
  •  栀梦
    栀梦 (楼主)
    2020-11-22 01:52

    There is another way in ES6, using Array.from which takes 2 arguments, the first is an arrayLike (in this case an object with length property), and the second is a mapping function (in this case we map the item to its index)

    Array.from({length:10}, (v,i) => i)
    

    this is shorter and can be used for other sequences like generating even numbers

    Array.from({length:10}, (v,i) => i*2)
    

    Also this has better performance than most other ways because it only loops once through the array. Check the snippit for some comparisons

    // open the dev console to see results
    
    count = 100000
    
    console.time("from object")
    for (let i = 0; i i )
    }
    console.timeEnd("from object")
    
    console.time("from keys")
    for (let i =0; i

提交回复
热议问题