簡體   English   中英

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

[英]How to iterate through specific indexes in Javascript?

我試圖弄清楚如何只遍歷javascript中列表的特定部分。

在Python中,我這樣做是這樣的:

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

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

我的問題是如何在JavaScript中編寫類似的for循環?

可以遍歷需要切片名單

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)
})

如果您的目標是存檔以下項的match結果:

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

只需使用array.prototype.slice

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

但是,如果您的目標是做出相同的努力 (循環),則可以執行以下任何一種技術:

您可以執行如下循環

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

另一種方法是切片數組:( array.prototype.slice

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

也許在...中使用...

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

甚至使用slice和forEach: array.prototype.forEach

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

也許還使用箭頭功能

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM