![](/img/trans.png)
[英]how to iterate over specific indexes and check values in javascript/angular
[英]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.