Home > Mobile >  NodeJS - How do I make from python 'for _ in range(number)' in NodeJS/JavaScript
NodeJS - How do I make from python 'for _ in range(number)' in NodeJS/JavaScript

Time:01-21

In python3x I'm using a simple code:

for i in range(1, 10):
    print(i)

I tried using Array function on NodeJS/JavaScript:

const LIST = [];
const Range = Array(10).fill("0, 10", 0, 10)
LIST.push(Range);

console.log(LIST);

But it seems it just gonna give output:

[
  [
    '0, 10', '0, 10',
    '0, 10', '0, 10',
    '0, 10', '0, 10',
    '0, 10', '0, 10',
    '0, 10', '0, 10'
  ]
]

How do I make it gives output from 1 to 10?

CodePudding user response:

Why... not just use a plain for loop?

for(let i = 1; i < 10; i  ) {
  console.log(i);
}

CodePudding user response:

Array() fills the array with nothing but gives it a certain length, so filling it with null makes it [null, null, ...]. Mapping the array is similar to mapping in python, you loop through each item in the array and return the current index 1. That creates an array [1, 2, 3, 4 ..., 10]

const Range = Array(10).fill(null).map((_, i) => i   1);

console.log(Range);

CodePudding user response:

The equivalent to for i in range(x, y) is for (let i = x; i < y; i ):

for (let i = 1; i < 10; i  ) {
  console.log(i)
}

Output is 1, 2, 3, 4, 5, 6, 7, 8, 9 just as it was in your Python example.

See docs.

CodePudding user response:

In short, what you're describing is an array where the index is also the value. That can be achieved with this little line:

const array = Array(10).fill(0).map((zero, index) => index)

console.log(array) // [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ]

In short, it does this:

  1. Array(10): Make an array of length 10, which is empty.
  2. .fill(0): Fill the array with zeros (could be anything).
  3. .map((z, i) => i): Replace each value (zero) with its index (0, 1, 2...)

CodePudding user response:

How about:

[...Array(10).keys()].map(x => x   1);

Explanation:

  • Array(10) gives an array of length 10.
  • .keys() gives the indices viz 0, 1, 2, ... 9.
  • .map(...) increments each index by 1, thus giving 1, 2, 3, ... 10

Try it out:

console.log([...Array(10).keys()].map(x => x   1))

  •  Tags:  
  • Related