简体   繁体   中英

How to iterate through specific indexes in Javascript?

I'm trying to figure out how to iterate through only a specific part of a list in javascript.

In Python i've done like this:

board = range(101)
answer = 92
match = []
low = answer - 2
high = answer + 2

for i in board[low:high + 1]:
    match.append(i)

My question is how do I write a similar for loop in javascript?

You can iterate over needed slice of the list

const board = new Array(101).fill().map((_, i) => i) //this way you can create range of [0..101]
...
board.slice(low, high+1).forEach(i=>{
  match.append(i)
})

In case that your goal is archiving the match result of:

for i in board[low:high + 1]:
   match.append(i)

Just use array.prototype.slice :

match = board.slice(low, high + 1);

But if your goal is to produce the same effort (making a loop) you could do any of this techniques:

You can do a loop like this:

for (let index = low; index < (high + 1); index++) {
  match.push(board[index])
}

Another way could be slicing the array: ( array.prototype.slice )

board = board.slice(low, high +1)
for (let index = 0; index < board.length; index++) {
  match.push(board[index])
}

And maybe using the for...in :

for (let item in board.slice(low, high + 1)) {
  match.push(item)
}

Or even using slice and a forEach: array.prototype.forEach

board.slice(low, high + 1).forEach(function(item){
  match.push(item)
});

And maybe also using an arrow function :

board.slice(low, high +1).forEach((i) = {
  match.push(i)
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM