Fastest way to fill an array with multiple value in JS. Can I pass a some pattern or function to method fill insted of a single value in JS? [duplicate]

邮差的信 提交于 2019-12-23 00:54:46

问题


Is it any way to create an array a selected size(for example 10) and immediately on the spot fill in it with some numbers specified pattern (1, 2, 3, OR 2, 4, 6 and so on) in one statement in JS?

let arr = new Array(10).fill( (a) => {a = 1; return a++; } );
console.log(arr); // Should be 1, 2, 3, 4, 5, 6, 7, 8, 9, 10

In other words can I pass a some patern or function to method fill insted of a single value.


回答1:


Actually there's much nicer idiom to create ranges: a spreaded Array constructor:

[...Array(n)]

creates an array of n undefined values. To get 0..n-1, just pick its keys:

[...Array(n).keys()]

for arbitrary ranges, feed it to map:

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

console.log(r)

see here: Does JavaScript have a method like "range()" to generate an array based on supplied bounds?

old answer:

yep, you're looking for Array.from:

r = Array.from({length: 10}, (_, i) => i + 1);

console.log(r)

How does this work? .from inspects its first argument (which can be any object) and picks its .length property. Then, it iterates from 0 to length - 1 and invokes the second argument with two parameters - a value (which is undefined unless the first argument contains a corresponding numeric property) and an index, which takes values from 0...length-1. In this example, we have a function that just returns an index + 1, thus giving us 1..length.

Here's a useful wrapper for the above:

let range = (from, to) => Array.from({length: to - from + 1}, _ => from++);

console.log(range(1, 10))

For ES5, the idiom is Array.apply(null, {length:N}):

r = Array.apply(null, {length: 10}).map(function(_, i) {
    return i + 1
})


来源:https://stackoverflow.com/questions/48962891/fastest-way-to-fill-an-array-with-multiple-value-in-js-can-i-pass-a-some-patter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!