我正在努力以某種方式迭代陣列。我在這里閱讀了很多帖子,但無法使其正常作業。
我有一個art_stuff這樣的陣列:
[
{
"block": 0,
"amt": 5
},
{
"block": 1,
"amt": 1
},
{
"block": 2,
"amt": 2
},
{
"block": 3,
"amt": 3
},
{
"block": 4,
"amt": 4
}
]
像這樣的 JSON 回應:
"products":[{
"id":1, //0
"id":2, //1
"id":3, //2
"id":4, //3
"id":5, //4
"id":6, //5
"id":7, //6
etc ....
在$.each我第一次回圈陣列。陣列中的amt是我從 JSON 回應中需要的 id 數量。例如:
Block 0需要來自 JSON 回應的 5 個 id。這就是索引 0 - 4(= id 1 到 id 5)Block 1需要 1 個 id,從塊 0 停止的地方開始,所以這是索引 5(= id 6)Block 2需要 2 個 id,從塊 1 停止的地方開始,所以這是索引 6 - 7(= id 7 和 id 8)等....
所以基本上每個塊都在前一個塊停止的地方開始回圈。
例如:
$.getJSON(url-to-json, function(data) {
........
var start_count = 0
var end_count = 0
$.each(art_stuff, function(index, art_block){
start_count = start_count art_block.amt
end_count = start_count 1
console.log('block_' art_block.block ' starts at: ' start_count ', and ends at: ' end_count)
//var prods = data.products.slice(start_count, end_count)
預期結果將是:
block_0 starts at: 0, and ends at: 4
block_1 starts at: 5, and ends at: 5
block_2 starts at: 6, and ends at: 7
block_3 starts at: 8, and ends at: 10
etc...
我不明白如何創建正確的起點和終點來分割 JSON 回應。
非常感謝任何幫助!
uj5u.com熱心網友回復:
您可以更改這兩行:
start_count = start_count art_block.amt
end_count = start_count 1
到
end_count = start_count art_block.amt - 1
然后在你$.each添加的最后
start_count = end_count 1;
一起,給予:
var art_stuff = [{
"block": 0,
"amt": 5
},
{
"block": 1,
"amt": 1
},
{
"block": 2,
"amt": 2
},
{
"block": 3,
"amt": 3
},
{
"block": 4,
"amt": 4
}
]
var start_count = 0
var end_count = 0
$.each(art_stuff, function(index, art_block) {
end_count = start_count art_block.amt - 1;
console.log('block_' art_block.block ' starts at: ' start_count ', and ends at: ' end_count)
//... other code
start_count = end_count 1; // ready for next iteration
}); // end of $.each
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/460585.html
上一篇:帶有資料框位置的JSON
