開発環境
- macOS Sierra - Apple (OS)
- Emacs (Text Editor)
- JavaScript (プログラミング言語)
- Safari(Web browser)
Head First JavaScript Programming (Eric T. Freeman (著)、Elisabeth Robson (著)、O'Reilly Media)の Chapter 4.(Arrays - Putting Some Order in Your Data)、How to iterate over an array の SHARPEN YOUR PENCIL(No. 2733) を取り組んでみる。
SHARPEN YOUR PENCIL(No. 2733)
コード(Emacs)
HTML5
<button id="run0">run</button><button id="clear0">clear</button> <pre id="output0"></pre> <script src="sample6.js"></script>
JavaScript
let btn0 = document.querySelector('#run0'), btn1 = document.querySelector('#clear0'), pre0 = document.querySelector('#output0'); let getBestResults1 = (scores, highScore) => { let bestSolutions = []; for (let i = 0; i < scores.length; i += 1) { if (scores[i] === highScore) { bestSolutions.push(i); } } return bestSolutions; }; let getBestResults2 = (scores, highScore) => { let bestSolutions = []; scores.forEach((score, i) => { if (score === highScore) { bestSolutions.push(i); } }); return bestSolutions; }; let output = () => { let scores = []; for (let i = 0; i < 36; i += 1) { scores.push(Math.floor(Math.random() * 10)); } let highScore = -1; let output; scores.forEach((score, i) => { output = `Bubble solution #${i} scores: ${scores[i]}\n`; pre0.textContent += output; if (score > highScore) { highScore = score; } }); pre0.textContent += `Bubbles tests: ${scores.length}\n`; pre0.textContent += `best solutions 1: ${getBestResults1(scores, highScore)}\n`; pre0.textContent += `best solutions 2: ${getBestResults2(scores, highScore)}\n`; }; btn0.onclick = output; btn1.onclick = () => { pre0.textContent = ''; }; output();
0 コメント:
コメントを投稿