How to create an array containing 1…N

后端 未结 30 1537
旧时难觅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:53

    If I get what you are after, you want an array of numbers 1..n that you can later loop through.

    If this is all you need, can you do this instead?

    var foo = new Array(45); // create an empty array with length 45
    

    then when you want to use it... (un-optimized, just for example)

    for(var i = 0; i < foo.length; i++){
      document.write('Item: ' + (i + 1) + ' of ' + foo.length + '
    '); }

    e.g. if you don't need to store anything in the array, you just need a container of the right length that you can iterate over... this might be easier.

    See it in action here: http://jsfiddle.net/3kcvm/

提交回复
热议问题