Difference between revisions of "World Factbook"
Jump to navigation
Jump to search
Line 53: | Line 53: | ||
* Use Math.random() to pick a country at random | * Use Math.random() to pick a country at random | ||
* Note that because of the way the scoring works you should not expect to get 100% | * Note that because of the way the scoring works you should not expect to get 100% | ||
The sample code shows a random country beginning with 'A' | |||
<div class=qu> | <div class=qu> | ||
<pre class=usr> | <pre class=usr> | ||
fetch('/worldl.json') | |||
.then((r)=>r.json()) | |||
.then((r)=>{ | |||
let alist = r.filter(c=>c.name[0]==='A'); | |||
let randomNumber = Math.floor(Math.random()*alist.length); | |||
let randomCountry = africa[randomNumber]; | |||
document.body.innerText = randomCountry.name; | |||
}); | |||
</pre> | </pre> | ||
<pre class=ans> | <pre class=ans> | ||
Line 60: | Line 69: | ||
.then((r)=>r.json()) | .then((r)=>r.json()) | ||
.then((r)=>{ | .then((r)=>{ | ||
let africa = r.filter(c=>c.continent=='Africa'); | let africa = r.filter(c=>c.continent==='Africa'); | ||
let randomNumber = Math.floor(Math.random()*africa.length); | let randomNumber = Math.floor(Math.random()*africa.length); | ||
let randomCountry = africa[randomNumber]; | let randomCountry = africa[randomNumber]; |
Revision as of 09:49, 22 January 2022
Get a button for each letter
- Show a button for each letter that a country can begin with
- You can use a Set to remove duplicates from a list.
fetch('/worldl.json') .then((r)=>r.json()) .then((r)=>{ let letters = r.map(c=>c.name[0]); for(let a of letters){ let b = document.createElement('button'); b.innerText = a; document.body.append(b); } });
fetch('/worldl.json') .then((r)=>r.json()) .then((r)=>{ let letters = new Set(r.map(c=>c.name[0])); for(let a of letters){ let b = document.createElement('button'); b.innerText = a; document.body.append(b); } });
Get a button for each continent
- Show a button for each continent
fetch('/worldl.json') .then((r)=>r.json()) .then((r)=>{ let letters = new Set(r.map(c=>c.continent)); for(let a of letters){ let b = document.createElement('button'); b.innerText = a; document.body.append(b); } });
Pick a random country from Africa
- Use Math.random() to pick a country at random
- Note that because of the way the scoring works you should not expect to get 100%
The sample code shows a random country beginning with 'A'
fetch('/worldl.json') .then((r)=>r.json()) .then((r)=>{ let alist = r.filter(c=>c.name[0]==='A'); let randomNumber = Math.floor(Math.random()*alist.length); let randomCountry = africa[randomNumber]; document.body.innerText = randomCountry.name; });
fetch('/worldl.json') .then((r)=>r.json()) .then((r)=>{ let africa = r.filter(c=>c.continent==='Africa'); let randomNumber = Math.floor(Math.random()*africa.length); let randomCountry = africa[randomNumber]; document.body.innerText = randomCountry.name; });