I want to create an array of numbers in a specific range in JavaScript.

Asked 1 years ago, Updated 1 years ago, 31 views

To create an array with values from 3 to 6, Ruby can do the following:

irb(main): 001:0> [*3..6]
=> [3,4,5,6]

How can I do this with JS?

javascript

2022-09-30 19:53

3 Answers

I'm not very good at it, but it seems that there is no answer, so I will answer.
There seems to be no way to express serial numbers like Ruby.
It was possible to:

start=3
end = 6
newArray(end-start+1).fill(null).map(_,i)=>i+start)
// [3, 4, 5, 6]

The following is helpful, so I will write it down.
https://qiita.com/Nossa/items/e420c15175d87cec079e


2022-09-30 19:53

One method is to use the Array.prototype.keys and Array.prototype.map methods.

{
  const start = 3;
  constend=6;
  [...Array(end-start+1).keys()].map(e=>e+start);//=>Array(4)[3,4,5,6]
}

There are already answers to similar methods, but you can also use the Array.prototype.fill and Array.prototype.map methods.

{
  const start = 3;
  constend=6;
  Array(end-start+1).fill(start).map(x,y)=>x+y);//=>Array(4)[3,4,5,6]
}

You can also use the Array.from method.

{
  const start = 3;
  constend=6;
  Array.from(Array(end-start+1),(_,i)=>i+start);//=>Array(4)[3,4,5,6]
}

You can also use spread syntax and generators.

{
  const start = 3;
  constend=6;
  [...(function*(x,y){while(x<=y)yield x++})(start,end)];//=>Array(4)[3,4,5,6]
}


2022-09-30 19:53

The Array.prototype system has already been optimized, so from another aspect.
Many Array.prototype methods handle only elements with a value, so you must substitute the value beforehand.

To set the number of loops to n times, write:

{
  const start = 3, end = 6;
  const result=[];
  for(leti=start;i<=end;i++)result.push(i);
  console.log(result); // [3,4,5,6]
}

{
  const start = 3, end = 6;
  const result=[];
  let i = start;
  while(i<=end)result.push(i++);
  console.log(result); // [3,4,5,6]
}

It's a standard "repeat syntax" that everyone knows, but I think it's a simple code without habit.

Dear Re:user11343782


2022-09-30 19:53

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.