简体   繁体   English

如何遍历Javascript中的特定索引?

[英]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. 我试图弄清楚如何只遍历javascript中列表的特定部分。

In Python i've done like this: 在Python中,我这样做是这样的:

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? 我的问题是如何在JavaScript中编写类似的for循环?

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: 如果您的目标是存档以下项的match结果:

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

Just use array.prototype.slice : 只需使用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 ) 另一种方法是切片数组:( 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 甚至使用slice和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)
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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