# 如何创建一个包含1…N的数组

2020/09/18 03:31 · javascript ·  · 0评论

``````var foo = [];

for (var i = 1; i <= N; i++) {
foo.push(i);
}``````

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

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

``````Array.from(Array(10).keys())
//=> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]``````

``````[...Array(10).keys()]
//=> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]``````

``````Array.from({length: 10}, (_, i) => i + 1)
//=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]``````

``````var N = 10;
Array.apply(null, {length: N}).map(Number.call, Number)``````

``Array.apply(null, {length: N}).map(Function.call, Math.random)``

### 说明

`Array.apply(null, [undefined, undefined, undefined])`等价于`Array(undefined, undefined, undefined)`，产生一个三元素数组并分配`undefined`给每个元素。

``````function Array() {
if ( arguments.length == 1 &&
'number' === typeof arguments[0] &&
arguments[0] >= 0 && arguments &&
arguments[0] < 1 << 32 ) {
return [ … ];  // array of length arguments[0], generated by native code
}
var a = [];
for (var i = 0; i < arguments.length; i++) {
a.push(arguments[i]);
}
return a;
}``````

``````function Array() {
var a = [];
for (var i = 0; i < /* arguments.length = */ N; i++) {
a.push(/* arguments[i] = */ undefined);
}
return a;
}``````

`callback`仅对已分配值的数组索引调用；对于已删除或从未分配值的索引，不会调用它。

## 使用ES6的多种方式

### 使用扩展运算符（`...`）和密钥方法

``[ ...Array(N).keys() ].map( i => i+1);``

### 填充/贴图

``Array(N).fill().map((_, i) => i+1);``

### Array.from

``Array.from(Array(N), (_, i) => i+1)``

### Array.from和`{ length: N }`黑客

``Array.from({ length: N }, (_, i) => i+1)``

### 关于广义形式的注释

``[ ...Array(N).keys() ].map(f)``

## 例子：

``````Array.from({length: 5}, (v, k) => k+1);
// [1,2,3,4,5]``````

### 具有自定义初始化函数的更通用的示例，`f`即

``[ ...Array(N).keys() ].map((i) => f(i))``

``[ ...Array(N).keys() ].map(f)``

``````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 Array
foo[ Math.floor(foo.length/2) ] = 'value' // places value in the middle of the array
*/``````

## ES6

### 传播

``var foo = [ ...Array(N).keys() ];``

### 填充/贴图

``var foo = Array(N).fill().map((v,i)=>i);``

### Array.from

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

1. 如果索引可用，则可以将其简单地加一（例如`++i`）。
2. 在不使用索引的情况下（可能是更有效的方法）是创建数组，但使N代表N + 1，然后移到最前面。

因此，如果您需要100个数字：

``let arr; (arr=[ ...Array(101).keys() ]).shift()``

`Array(N).fill().map((e,i)=>i+1);`

http://jsbin.com/molabiluwa/edit?js，控制台

``````console.log(
Array(45).fill(0).map((e,i)=>i+1)
);``````

``````// _.range([start], stop, [step])

_.range(10); // => [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
_.range(1, 11); // => [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
_.range(0, 30, 5); // => [0, 5, 10, 15, 20, 25]
_.range(0, -10, -1); //  => [0, -1, -2, -3, -4, -5, -6, -7, -8, -9]
_.range(0); // => []``````
``````function range(start, end) {
var foo = [];
for (var i = start; i <= end; i++) {
foo.push(i);
}
return foo;
}``````

``var foo = range(1, 5);``

``````function range(start, count) {
if(arguments.length == 1) {
count = start;
start = 0;
}

var foo = [];
for (var i = 0; i < count; i++) {
foo.push(start + i);
}
return foo;
}``````

``[...Array(5)].map((_,i) => i);``

``[...Array(255).keys()].map(x => x + 1)``

127，Int8，

255，Uint8，

32,767，Int16，

65,535，Uint16，

2,147,483,647，Int32，

4,294,967,295，Uint32。

（基于最大整数值），还有更多关于Typed Arrays的信息

``(new Uint8Array(255)).map((\$,i) => i + 1);``

``for(var i = 0, arr = new Uint8Array(255); i < arr.length; i++) arr[i] = i + 1;``

``````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 want
range(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
);``````

``range(1,14000);``

``````new Array(/*any number which you want*/)
.join().split(',')
.map(function(item, index){ return ++index;})``````

``````new Array(10)
.join().split(',')
.map(function(item, index){ return ++index;})``````

``[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]``

``[...Array(10)].map((_, i) => i + 1)``

``console.log([...Array(10)].map((_, i) => i + 1))``

``````d3.range(5)
[0, 1, 2, 3, 4]``````

``````d3.range(1, 5+1)
[1, 2, 3, 4, 5]``````

``var a=[],b=N;while(b--)a[b]=b+1;``

``````var arr=(function(a,b){while(a--)b[a]=a;return b})(10,[]);
//arr=[0,1,2,3,4,5,6,7,8,9]``````

``````var arr=(function(a,b){while(a--)b[a]=a+1;return b})(10,[]);
//arr=[1,2,3,4,5,6,7,8,9,10]``````

``````function range(a,b,c){c=[];while(a--)c[a]=a+b;return c}; //length,start,placeholder
var arr=range(10,5);
//arr=[5,6,7,8,9,10,11,12,13,14]``````

1. `while` 是最快的循环

2. 直接设置比 `push`

3. `[]` 快于 `new Array(10)`

4. 简短...看第一个代码。然后在这里查看所有其他功能。

``for(var a=[],b=7;b>0;a[--b]=b+1); //a=[1,2,3,4,5,6,7]``

``for(var a=[],b=7;b--;a[b]=b+1); //a=[1,2,3,4,5,6,7]``

`_.range([start=0], end, [step=1])`

``````_.range(4);
// ➜ [0, 1, 2, 3]

_.range(-4);
// ➜ [0, -1, -2, -3]

_.range(1, 5);
// ➜ [1, 2, 3, 4]

_.range(0, 20, 5);
// ➜ [0, 5, 10, 15]

_.range(0, -4, -1);
// ➜ [0, -1, -2, -3]

_.range(1, 4, 0);
// ➜ [1, 1, 1]

_.range(0);
// ➜ []``````

``````const array = [...Array(5).keys()]
console.log(array)``````

``````// `n` is the size you want to initialize your array
// `null` is what the array will be filled with (can be any other value)
Array(n).fill(null)``````

``(function(n){for(a=[];n--;a[n]=n+1);return a})(10)``

``[...Array(10).keys()]``

ES6中还有另一种方法，使用Array.from，它带有 2个参数，第一个是arrayLike（在这种情况下是具有`length`属性的对象），第二个是映射函数（在这种情况下，我们将项目映射到其索引）

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

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

``````// open the dev console to see results

count = 100000

console.time("from object")
for (let i = 0; i<count; i++) {
range = Array.from({length:10}, (v,i) => i )
}
console.timeEnd("from object")

console.time("from keys")
for (let i =0; i<count; i++) {
range = Array.from(Array(10).keys())
}
console.timeEnd("from keys")

console.time("apply")
for (let i = 0; i<count; i++) {
range = Array.apply(null, { length: 10 }).map(function(element, index) { return index; })
}
console.timeEnd("apply")``````

## 在ES6中：

``Array.from({length: 1000}, (_, i) => i).slice(1);``

``Array.from({length:1000}, Number.call, i => i + 1)``

``Uint8Array.from({length:10}, Number.call, i => i + 1)``

## ES5：

``Array.apply(0, {length: 1000}).map(function(){return arguments[1]+1});``

``Array.apply(0,{length:1000}).map(Number.call,Number).slice(1)``

``Array.apply(0,{length:1000}).map(Number.call, Function("i","return i+1"))``

``Array(N).fill().map((_, i) => i + 1);``

`Array.from`轮流“孔”进入`undefined`这样`Array.map`按预期工作：

``Array.from(Array(5)).map((_, i) => i + 1)``
``````Array(...Array(9)).map((_, i) => i);

console.log(Array(...Array(9)).map((_, i) => i))``````
``for(var i,a=[i=0];i<10;a[i++]=i);``

a = [1、2、3、4、5、6、7、8、9、10]

``const gen = N => [...(function*(){let i=0;while(i<N)yield i++})()]``

``gen(4) // [0,1,2,3]``

``````const gen = N => [...(function*(){let i=0;
while(i++<N) yield Math.random()
})()]``````

``````const slow = N => new Array(N).join().split(',').map((e,i)=>i*5)
// [0,5,10,15,...]``````

``const fast = N => [...(function*(){let i=0;while(i++<N)yield i*5})()]``

``````Example-One: Array(10).fill(0).map((e,i)=>i+1)

Result-One: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Example-Two: Array(100/10).fill(0).map((e,i)=>(i*10)+10)

Result-Two:[10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
``````

Array.from（arrayLike [，mapFn [，thisArg]]）

``Array.from(Array(10), (_, i) => i)``

``````var arr = Array.from(Array(10), (_, i) => i);
document.write(arr);``````

``````function sequence(max, step = 1) {
return {
[Symbol.iterator]: function* () {
for (let i = 1; i <= max; i += step) yield i
}
}
}

console.log([...sequence(10)])``````
``Array.from({ length: (stop - start) / step + 1}, (_, i) => start + (i * step));``

``const generateArray = n => [...Array(n)].map((_, index) => index + 1);``

# 说明：

• `Array(3) // [undefined × 3]`生成长度为n = 3的数组。不幸的是，这个数组对我们几乎没有用，所以我们必须…
• `Array.apply(0,Array(3)) // [undefined, undefined, undefined]`使数组可迭代。注意：null最常见的是apply的第一个arg，但0则更短。
• `Object.keys(Array.apply(0,Array(3))) // ['0', '1', '2']` 然后获取数组的键（之所以起作用，是因为Arrays是typeof数组是具有键索引的对象。
• `Object.keys(Array.apply(0,Array(3))).map(Number) // [0, 1, 2]` 并映射到键，将字符串转换为数字。