![]() |
easy numbered array generation
i have been search forever for a way to make a numbered array using only native functions and without looping.
i had figured out a long, convoluted way of doing it with eval and bind(), but it was not pretty. the one trick to this native functionality is that you have to specify a number one more than the ceiling you want, but that's not the end of the world... the method is related to the popular String repeat trick: Code:
Array(101).join(",").split(",").join("hello world \t")here is the numbered array code: Code:
Object.keys( new String( Array(101) ) ).map(Number)Code:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99]for you cut-and-paste pleasure, here are some working reusables: as a function Code:
function arr(n) {Code:
arr(10) // === [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]as a mutating array prototype Code:
Array.prototype.numbered = function _numbered(n) {and as a hidden mutating array prototype Code:
Object.defineProperty(Array.prototype,"numbered", function _numbered(n) {usage Code:
["a","b","c"].numbered() // === [0, 1, 2] |
should work equally well:
PHP Code:
|
Quote:
PHP Code:
|
| All times are GMT +1. The time now is 10:54 PM. |
Powered by vBulletin®
Copyright ©2000 - 2013, Jelsoft Enterprises Ltd.