Задача
Я сталкиваюсь с тем, что, как мне кажется, является проблемой области действия этих двух for loops
Каждый из них выполняет итерацию по разному количеству элементов.
- Я пытаюсь выяснить, как ссылаться на итератор
i
из первого цикла во втором цикле.
- В частности, я объединяю строку в остальной части оператора if во втором цикле, и мне нужно иметь возможность ссылаться на
i
и j
Разъяснение
Я пытаюсь создать сетку 11 x 8 на 88 квадратов. Им нужно иметь определенный класс, который будет окрашивать квадраты. Каждый квадрат имеет идентификатор данных от 1 до 88, который определяет их размещение в сетке. Состояния / квадраты, которые должны быть закрашены на основе данных, не являются последовательными, как видно из фрагмента data.json
.
Петля № 1
я начинаю с 0, 1, 2 ... 50
for (i = 0; i < data.length; i++) {}
Петля № 2
j начинается с 1, 2, 3 ... 88
for (j = 1; j < squaresTotal + 1; j++) {
// If it doesn't exist, push those values into the an array
if (states.indexOf(j) === -1){
blanks.push(j);
$("<div class='square is-white' data-id='" + j + "'></div>").appendTo(".map");
} else {
$("<div class='square " + data[i].class + "' data-id='" + j + "'><p class='square__state'>" + data[i].abbr + "</p></div>").appendTo(".map");
}
}
scripts.js
<script>
$(function(){
$.ajax({
url: 'data.json',
method: 'GET',
dataType: 'json'
}).then(main);
});
function main(data) {
// The parent container that holds the map
let map = $(".map");
// IDs of the states and the blank tiles
let blanks = [];
let states = [];
// Contains data for all 50 states
for (i = 0; i < data.length; i++) {
// Data is sorted by the rank field in descending order
data.sort(function(a, b){
return a['rank'] - b['rank'];
});
// Fields for the data table below the map
// Numbered rank (i.e. 1, 2, 3)
let rank = data[i].rank;
// Full state name (i.e. Alaska)
let state = data[i].state;
// Total consumer electric power
let value = (data[i].total_consumption_electric_power).toLocaleString();
// Each row in the table contains a rank, state and value
if (rank) {
$("<tr><th scope='row'>" + data[i].rank + "</th><td>" + data[i].state + "</td><td>" + value + "</td></tr>").appendTo("tbody");
}
// Push the ids to the empty states array
states.push(data[i].id);
}
// The grid is 11 by 8 for a total of 88 squares
const squaresTotal = 88;
for (j = 1; j < squaresTotal + 1; j++) {
// If it doesn't exist, push those values into the an array
if (states.indexOf(j) === -1){
blanks.push(j);
$("<div class='square is-white' data-id='" + j + "'></div>").appendTo(".map");
} else {
$("<div class='square " + data[i].class + "' data-id='" + j + "'><p class='square__state'>" + data[i].abbr + "</p></div>").appendTo(".map");
}
}
var pymChild = new pym.Child();
pymChild.sendHeight();
}
</script>
data.json (фрагмент)
[
{
"id": 1,
"state": "Alaska",
"rank": "",
"abbr": "AK",
"class": "square-1",
"total_consumption_electric_power": 707913
},
{
"id": 11,
"state": "Maine",
"rank": "",
"abbr": "ME",
"class": "square-1",
"total_consumption_electric_power": 62360
},
{
"id": 17,
"state": "Wisconsin",
"rank": "",
"abbr": "WI",
"class": "square-5",
"total_consumption_electric_power": 19482575
}
]