i want to sort json data using for loop but there is an error in line no. 28.
If anyone has a solution to this problem, please help me
Without actual code it’s hard to tell but make sure objects in your countries array have capital properties.
if you have idea please reply
const app = document.getElementById('root');
const container = document.createElement('div');
container.setAttribute('class', 'container');
app.appendChild(container);
var countries,i,name;
fetch("https://restcountries.eu/rest/v2/all")
.then(function(res){
return res.json();
})
.then(function(data){
intitialize(data);
})
.catch(function(err){
console.log("Error:", err);
});
function intitialize(countriesData){
countries=countriesData;
for(i=0;i<countries.length;i++){
const card = document.createElement('div');
card.setAttribute('class', 'card');
const but=document.createElement('button');
const nam=document.createTextNode(`${countries[i].name}`);
but.onclick=function(){
const a=`${countries[i].capital}`;
const b=`${countries[i].area}`;
const c=`${countries[i].population}`;
var queryString = "?" +a+ "&" +b+"&"+c;
window.location.href = "display.html" + queryString;
}
container.appendChild(card);
but.appendChild(nam);
card.appendChild(but);
}
}
function process(){
var queryString = decodeURIComponent(window.location.search);
queryString = queryString.substring(1);
var queries = queryString.split("&");
document.getElementById("par").innerHTML = queries[0];
document.getElementById("b1").innerHTML = queries[1];
document.getElementById("b2").innerHTML = queries[2];
}
when i am using foreach loop {
foreach(country=>…line no 28:const a=country.captial;…}then there is no problem but when i am using for loop it shows error.
This line is causing the error.
You need to define the variable i
with let
, like so:
for(let i = 0; i < countries.length; i++) {
This is a problem because, currently, i
is defined as a global variable and at the end of a loop its value will be countries.length + 1
(250 in this case).
The var
will also not work because variable defined with var
is function-scoped, not block scoped like in let
.
Of course, yours won’t work because of the semicolon between the i<
and the countries.length
.
Good catch Thanks!
thank you very much sir:slightly_smiling_face: