Od pole k objektům
Začněme úlohou:
<!DOCTYPE html> <html lang="cs"> <head> <meta charset="utf-8" /> <title>Titulek</title> <style> /* Vychozi CSS stylovani prijde sem*/ /* */ </style> </head> <body> <div id="vystup"></div> <script> /* <![CDATA[ */ var tramvaje = [15, 20, 12, 20] var nalezeno = 0 for(var i=0;i<tramvaje.length;i++){ //vykona se pro kazdy prvek if(tramvaje[i] == '20'){ nalezeno++ } } document.getElementById('vystup').innerHTML = nalezeno /* ]]> */ </script> </body> </html>
<!DOCTYPE html> <html lang="cs"> <head> <meta charset="utf-8" /> <title>Titulek</title> <style> /* Vychozi CSS stylovani prijde sem*/ td {border: 1px solid black; padding:0.3em} table {border-collapse: collapse} /* */ </style> </head> <body> <table id="vystup"><tr><th>Tramvaj</th><th>Pozorování</th></tr></table> <script> /* <![CDATA[ */ var tramvaje = [15, 20, 12, 20, 15, 7, 15, 20, 7, 7, 7] // Ukol 2 // pocet pozorovani tramvaje 20, 15, 7 // Ukol 3 // naleznete tramvaj s nejvice pozorovanimi var maximalniHodnota = 0 var tramvajSMaximalniHodnotou = 0 for(var cilovaTramvaj = 1; cilovaTramvaj < 40; cilovaTramvaj++){ var nalezeno = 0 for(var i=0;i<tramvaje.length;i++){ //vykona se pro kazdy prvek if(tramvaje[i] == cilovaTramvaj){ nalezeno++ } } if(nalezeno > maximalniHodnota){ maximalniHodnota = nalezeno tramvajSMaximalniHodnotou = cilovaTramvaj } // "nalezeno" je pocet pozorovani tramvaje "cilovaTramvaj" document.getElementById('vystup').innerHTML+= "<tr><td>"+cilovaTramvaj+"</td><td>"+nalezeno+"</td></tr>" } //document.getElementById('vystup').innerHTML = tramvajSMaximalniHodnotou+":"+maximalniHodnota /* ]]> */ </script> </body> </html>
S polem
<!DOCTYPE html> <html lang="cs"> <head> <meta charset="utf-8" /> <title>Titulek</title> <style> /* Vychozi CSS stylovani prijde sem*/ td {border: 1px solid black; padding:0.3em} table {border-collapse: collapse} /* */ </style> </head> <body> <table id="vystup"><tr><th>Tramvaj</th><th>Pozorování</th></tr></table> <script> /* <![CDATA[ */ tramvaje = [15, 20, 12, 20, 15, 7, 15, 20, 7, 7, 7] var pocetVyskytuTramvaje = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0] for(var i = 0; i < tramvaje.length; i++){ var cisloTramvaje = tramvaje[i] pocetVyskytuTramvaje[cisloTramvaje]++ } // Vypsat kolikrat projela konkretni tramvaj console.log("Dvacitka projela: " + pocetVyskytuTramvaje[20]) // Najit maximum ... ? /* ]]> */ </script> </body> </html>