var foo = new Array(N); // where N is a positive integer
/* this will create an array of size, N, primarily for memory allocation,but does not create any defined values
foo.length // size of Arrayfoo[ Math.floor(foo.length/2) ] = 'value' // places value in the middle of the array*/
当然,var array = new Array(N);会给你一个大小为N的数组,但键和值将是相同的……然后要将数组缩短到大小为M,请使用array.length = M……但对于一些附加功能,请尝试:
function range(){// This function takes optional arguments:// start, end, increment// start may be larger or smaller than end// Example: range(null, null, 2);
var array = []; // Create empty array
// Get arguments or set default values:var start = (arguments[0] ? arguments[0] : 0);var end = (arguments[1] ? arguments[1] : 9);// If start == end return array of size 1if (start == end) { array.push(start); return array; }var inc = (arguments[2] ? Math.abs(arguments[2]) : 1);
inc *= (start > end ? -1 : 1); // Figure out which direction to increment.
// Loop ending condition depends on relative sizes of start and endfor (var i = start; (start < end ? i <= end : i >= end) ; i += inc)array.push(i);
return array;}
var foo = range(1, -100, 8.5)
for(var i=0;i<foo.length;i++){document.write(foo[i] + ' is item: ' + (i+1) + ' of ' + foo.length + '<br/>');}
上述产出:
1是项目:12中的1 -7.5是项目:2 of 12 -16是项目:3 of 12 -24.5是项目:4 of 12 -33是项目:12中的5 -41.5是项目:12中的6 -50是项目:12中的7 -58.5是项目:12中的8 -67是项目:12中的9 -75.5是项目:10 of 12 -84是项目:12中的11 -92.5是项目:12 of 12
// create range by NArray(N).join(0).split(0);
// create a range starting with 0 as the valueArray(7).join(0).split(0).map((v, i) => i + 1) // [1, 2, 3, 4, 5, 6, 7]
// A solution where you do not allocate a N sized array (ES6, with some flow annotation):function* zeroToN(N /* : number */)/* : Generator<number, void, empty> */ {for (let n = 0; n <= N; n += 1) yield n;}
// With this generation, you can have your arrayconsole.log([...zeroToN(10-1)])
// but let's define a helper iterator functionfunction mapIterator(iterator, mapping) {const arr = [];for (let result = iterator.next(); !result.done; result = iterator.next()) {arr.push(mapping(result.value));}return arr;}
// now you have a map function, without allocating that 0...N-1 array
console.log(mapIterator(zeroToN(10-1), n => n*n));
for(var i = 0, arr = new Uint8Array(255); i < arr.length; i++) arr[i] = i + 1;
在这个语句之后的任何时候,您都可以在当前范围内简单地使用变量“arr”;
如果你想做一个简单的函数(通过一些基本的验证):
function range(min, max) {min = min && min.constructor == Number ? min : 0;!(max && max.constructor == Number && max > min) && // boolean statements can also be used with void return types, like a one-line if statement.((max = min) & (min = 0)); //if there is a "max" argument specified, then first check if its a number and if its graeter than min: if so, stay the same; if not, then consider it as if there is no "max" in the first place, and "max" becomes "min" (and min becomes 0 by default)
for(var i = 0, arr = new (max < 128 ? Int8Array :max < 256 ? Uint8Array :max < 32768 ? Int16Array :max < 65536 ? Uint16Array :max < 2147483648 ? Int32Array :max < 4294967296 ? Uint32Array :Array)(max - min); i < arr.length; i++) arr[i] = i + min;return arr;}
//and you can loop through it easily using array methods if you wantrange(1,11).forEach(x => console.log(x));
//or if you're used to pythons `for...in` you can do a similar thing with `for...of` if you want the individual values:for(i of range(2020,2025)) console.log(i);
//or if you really want to use `for..in`, you can, but then you will only be accessing the keys:
for(k in range(25,30)) console.log(k);
console.log(range(1,128).constructor.name,range(200).constructor.name,range(400,900).constructor.name,range(33333).constructor.name,range(823, 100000).constructor.name,range(10,4) // when the "min" argument is greater than the "max", then it just considers it as if there is no "max", and the new max becomes "min", and "min" becomes 0, as if "max" was never even written);
const range = (from, to, step) =>[...Array(Math.floor((to - from) / step) + 1)].map((_, i) => from + i * step);
range(0, 9, 2);//=> [0, 2, 4, 6, 8]
// can also assign range function as static method in Array class (but not recommended )Array.range = (from, to, step) =>[...Array(Math.floor((to - from) / step) + 1)].map((_, i) => from + i * step);
Array.range(2, 10, 2);//=> [2, 4, 6, 8, 10]
Array.range(0, 10, 1);//=> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Array.range(2, 10, -1);//=> []
Array.range(3, 0, -1);//=> [3, 2, 1, 0]
作为迭代器
class Range {constructor(total = 0, step = 1, from = 0) {this[Symbol.iterator] = function* () {for (let i = 0; i < total; yield from + i++ * step) {}};}}
[...new Range(5)]; // Five Elements//=> [0, 1, 2, 3, 4][...new Range(5, 2)]; // Five Elements With Step 2//=> [0, 2, 4, 6, 8][...new Range(5, -2, 10)]; // Five Elements With Step -2 From 10//=>[10, 8, 6, 4, 2][...new Range(5, -2, -10)]; // Five Elements With Step -2 From -10//=> [-10, -12, -14, -16, -18]
// Also works with for..of loopfor (i of new Range(5, -2, 10)) console.log(i);// 10 8 6 4 2
仅作为发电机
const Range = function* (total = 0, step = 1, from = 0) {for (let i = 0; i < total; yield from + i++ * step) {}};
Array.from(Range(5, -2, -10));//=> [-10, -12, -14, -16, -18]
[...Range(5, -2, -10)]; // Five Elements With Step -2 From -10//=> [-10, -12, -14, -16, -18]
// Also works with for..of loopfor (i of Range(5, -2, 10)) console.log(i);// 10 8 6 4 2
// Lazy loaded wayconst number0toInf = Range(Infinity);number0toInf.next().value;//=> 0number0toInf.next().value;//=> 1// ...
从到带步骤/增量
使用迭代器
class Range2 {constructor(to = 0, step = 1, from = 0) {this[Symbol.iterator] = function* () {let i = 0,length = Math.floor((to - from) / step) + 1;while (i < length) yield from + i++ * step;};}}[...new Range2(5)]; // First 5 Whole Numbers//=> [0, 1, 2, 3, 4, 5]
[...new Range2(5, 2)]; // From 0 to 5 with step 2//=> [0, 2, 4]
[...new Range2(5, -2, 10)]; // From 10 to 5 with step -2//=> [10, 8, 6]
使用发电机
const Range2 = function* (to = 0, step = 1, from = 0) {let i = 0,length = Math.floor((to - from) / step) + 1;while (i < length) yield from + i++ * step;};
[...Range2(5, -2, 10)]; // From 10 to 5 with step -2//=> [10, 8, 6]
let even4to10 = Range2(10, 2, 4);even4to10.next().value;//=> 4even4to10.next().value;//=> 6even4to10.next().value;//=> 8even4to10.next().value;//=> 10even4to10.next().value;//=> undefined
对于TypeScript
class _Array<T> extends Array<T> {static range(from: number, to: number, step: number): number[] {return Array.from(Array(Math.floor((to - from) / step) + 1)).map((v, k) => from + k * step);}}_Array.range(0, 9, 1);
function A(N) {return Array.from({length: N}, (_, i) => i + 1)}
function B(N) {return Array(N).fill().map((_, i) => i+1);}
function C(N) {return Array(N).join().split(',').map((_, i) => i+1 );}
function D(N) {return Array.from(Array(N), (_, i) => i+1)}
function E(N) {return Array.from({ length: N }, (_, i) => i+1)}
function F(N) {return Array.from({length:N}, Number.call, i => i + 1)}
function G(N) {return (Array(N)+'').split(',').map((_,i)=> i+1)}
function H(N) {return [ ...Array(N).keys() ].map( i => i+1);}
function I(N) {return [...Array(N).keys()].map(x => x + 1);}
function J(N) {return [...Array(N+1).keys()].slice(1)}
function K(N) {return [...Array(N).keys()].map(x => ++x);}
function L(N) {let arr; (arr=[ ...Array(N+1).keys() ]).shift();return arr;}
function M(N) {var arr = [];var i = 0;
while (N--) arr.push(++i);
return arr;}
function N(N) {var a=[],b=N;while(b--)a[b]=b+1;return a;}
function O(N) {var a=Array(N),b=0;while(b<N) a[b++]=b;return a;}
function P(N) {var foo = [];for (var i = 1; i <= N; i++) foo.push(i);return foo;}
function Q(N) {for(var a=[],b=N;b--;a[b]=b+1);return a;}
function R(N) {for(var i,a=[i=0];i<N;a[i++]=i);return a;}
function S(N) {let foo,x;for(foo=[x=N]; x; foo[x-1]=x--);return foo;}
function T(N) {return new Uint8Array(N).map((item, i) => i + 1);}
function U(N) {return '_'.repeat(5).split('').map((_, i) => i + 1);}
function V(N) {return _.range(1, N+1);}
function W(N) {return [...(function*(){let i=0;while(i<N)yield ++i})()]}
function X(N) {function sequence(max, step = 1) {return {[Symbol.iterator]: function* () {for (let i = 1; i <= max; i += step) yield i}}}
return [...sequence(N)];}
[A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X].forEach(f=> {console.log(`${f.name} ${f(5)}`);})
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.20/lodash.min.js" integrity="sha512-90vH1Z83AJY9DmlWa8WkjkV79yfS2n2Oxhsi2dZbIv0nC4E6m5AbH8Nh156kkM7JePmqD6tcZsfad1ueoaovww==" crossorigin="anonymous"> </script>
This snippet only presents functions used in performance tests - it does not perform tests itself!