ゼロ秒JS-デジタル野球を実現(2)
44086 ワード
使用4-6複文(星空作業)
// 별찍기 1 ~ 5
let n = 1
while(n <= 5){
console.log('*'.repeat(n));
n ++
}
// 별찍기 5 ~ 1
let n = 0
while(n <= 5){
console.log('*'.repeat(5 - n));
n --
}
// 공백포함 별찍기
let n = 1
while(n <= 5){
console.log(' '.repeat(5 - n) + '*'.repeat(n))
n++
}
4-7スタージョブが正しい
// 별찍기 13531
let n = 4
while(n >= -4){
console.log('*'.repeat(5 - Math.abs(n)))
n -= 2
}
// 별찍기 다이아몬드
let n = 4
while(n >= -4){
console.log(' '.repeat(Math.abs(n)/2) + '*'.repeat(5 - Math.abs(n)))
n -= 2
}
4-8重複抽出なし
配列内のさまざまな方法を理解する
1)要素を追加、削除する方法:配列の先頭または末尾にメソッドを追加または削除します.
2)要素を自由に扱う方法
arr.splice():配列に要素を追加、削除、置換する方法.
arr.splice(indexNumber,deleteCount):arrのindexNumberからdeleteCountの数字と同じ要素を削除します.また、変数にspliceを加え、削除した値を返すことができます.
arr.splice(0,2,element 1,element 2):arrの0番インデックスから2つの要素を削除し、その位置をelement 1とelement 2で置き換えます.
arr.splice(2,0,element 1,element 2):arrの2番インデックスから0要素を削除し、element 1とelement 2を追加します.//deleteCountを0に設定すると、要素を削除せずに新しい要素を追加できます.
while(n <= 3){
const index = Math.floor(Math.random() * (10 - n))
answer.push(numbers[index])
numbers.splice(index,1)
n += 1
}
4-9 for文と配列の比較
JavaScriptの代表的な重複文:for,while
// example 1)
// n이 10보다 작거나 같을 때 까지 n에 1씩 더하고 콘솔에 출력한다.
for(let n = 1; n <= 10; n++){
console.log(n) // 1,2,3,4,5,6,7,8,9,10
}
2)while文の使用構成
// example 2)
// i가 10보다 작거나 같을 때 까지 i에 1씩 더하고 콘솔에 출력한다.
let i = 0
while(i <= 10){
console.log(i) // 0,1,2,3,4,5,6,7,8,9,10
i++
}
//example 3)
// n이 10보다 작거나 같을 때 까지 n에 1씩 더한 후 콘솔에 출력한다.
// 단, n이 5보다 같거나 크다면 **탈출한다**
let n = 0;
while (n <= 10) {
if (n >= 5) {
break;
}
console.log(n); // 0,1,2,3,4
n++;
}
//example 3)
// n이 10보다 작거나 같을 때 까지 n에 1씩 더한 후 콘솔에 출력한다.
// 단, n이 5보다 같거나 크다면 **탈출한다**
let n = 0;
while (n <= 10) {
n++;
if (n % 2 === 0) {
// n%2 === 0 : 2로 나눈 나머지가 0인 수, 즉 2의 배수이자 짝수 인 수를 제외하고 출력한다.
continue;
}
console.log(n);
}
3)比較アレイ4-10ストライク
// example 1)
// arr.forEach(callback(currentvalue[, index[, array]])[, thisArg])
//currentvalue === element //index === index // array === array
const arr = ['가', '나', '다', '라'];
arr.forEach(function(element, index, array){
console.log(`${array}의 ${index}번째 요소 : ${element}`);
});
/*
가,나,다,라의 0번째 요소 : 가
가,나,다,라의 1번째 요소 : 나
가,나,다,라의 2번째 요소 : 다
가,나,다,라의 3번째 요소 : 라
*/
// example 2)
// 숏코드
// 배열의 첫번째부터 마지막까지 반복하며 출력가능
array = ['엄마','아빠', '오빠']
array.forEach(family => console.log(family))
array.forEach(function(family){
template = `내가 사랑하는 ${family}`
console.log(template)
})
const arr = [1, 2, 3];
for (const item of arr) {
console.log(item); // 1, 2, 3
}
// example 1)
// for of 와 똑같은 코드를 적용했을 때 객체에 해당하는 key값이 출력된다. 배열로 따지면 index가 출력된다.
const arr = [1, 2, 3];
for (const item in arr) {
console.log(item); // 0, 1, 2
}
// example 2)
// 객체를 탐색할 경우
const obj = {
a: 1,
b: 2,
c: 3
};
for (const item in obj) {
console.log(item) // a, b, c
console.log(obj[item]) // 1,2,3
answer = obj[item]
console.log(`${item} : ${answer}`) // a:1, b:1, c:3
}
// example 1)
test = {
a: 1,
b: 2,
c: 3
};
console.log(Object.entries(test))
// [ [ 'a', 1 ], [ 'b', 2 ], [ 'c', 3 ] ]
//example 2)
const object1 = {
a: 'somestring',
b: 42
};
for (const [key, value] of Object.entries(object1)) {
console.log(`${key}: ${value}`);
}
test = [1,2,3,4]
for(const[index,element] of test.entries()){
console.log(index,element);
}
/*
0 1
1 2
2 3
3 4
*/
4-11テンプレート文字列(backtic)
logs.appendChild(document.createTextNode(strike + 'strike' + ball + 'ball'))
logs.appendChild(document.createTextNode(`${strike} strike ${ball} ball`))
4-12 appendChildとQ&A
完了したコード
<script>
const input = document.querySelector('#input');
const check = document.querySelector('#check');
const logs = document.querySelector('#logs');
// map이 나오면 함수형 프로그램
// let numbers = Array(10).fill().map(v,i => i)
let numbers = []
for(let n = 0; n <= 9; n++){
numbers.push(n)
}
let answer = []
let n = 0
for(let n = 0; n <= 3; n += 1){
const index = Math.floor(Math.random() * numbers.length)
answer.push(numbers[index])
numbers.splice(index,1)
}
console.log(answer)
let count = 0;
check.addEventListener('click', () => {
const value = input.value
if(value && value.length === 4){
if(answer.join('') === value){
logs.append(document.createTextNode('HR'))
input.value = ''
input.focus()
}else{
let strike = 0
let ball = 0
for(const [aIndex, aNumber] of answer.entries()){
for(const [iIndex, iString] of input.value.split('').entries()){
if(aNumber === Number(iString)){
if(aIndex === iIndex){
strike += 1
}else{
ball += 1
}
}
}
}
logs.append(`${input.value}: ${strike} strike ${ball} ball`, document.createElement('br'))
input.value = ''
input.focus()
if(count > 10){
logs.append(`Game Over: ${answer.join('')}`)
input.value = ''
input.focus()
}else{
count++
}
}
}else{
logs.append('에러 : 4개의 숫자를 작성해주세요.', document.createElement('br'))
input.value = ''
input.focus()
}
});
</script>
ソース:1) https://www.zerocho.com/category/JavaScript/post/57341f84420974fa1f92a761
2) https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Array/join
Reference
この問題について(ゼロ秒JS-デジタル野球を実現(2)), 我々は、より多くの情報をここで見つけました https://velog.io/@gparkkii/zerochojsstudy042テキストは自由に共有またはコピーできます。ただし、このドキュメントのURLは参考URLとして残しておいてください。
Collection and Share based on the CC Protocol