- .join(): 배열을 배열을 문자열로 결합하면, 해당 배열의 요소들이 문자열로 연결되어 하나의 문자열로 생성
this.answer = [ '1', '2','3' ];
this.answer.join('') = "123";
- .includes(): 주어진 문자열이 다른 문자열에 포함되어 있는지 여부를 불리언 값으로 반환
const mainString = "Hello, world!";
const substring = "world";
const isIncluded = mainString.includes(substring);
console.log(isIncluded);
<template>
<div id="root">
<h1>{{ result }}</h1>
<form @submit.prevent="onSubmitForm">
<input
type="text"
ref="focusInputbox"
minlength="4"
maxlength="4"
v-model="inputValue"
/>
<button type="submit">입력</button>
</form>
<div>시도 : {{ tries.length }}</div>
<ul>
<li v-for="t in tries" :key="{t}">
<div>{{ t.try }}</div>
<div>{{ t.result }}</div>
</li>
</ul>
</div>
</template>
<script>
const getNumbers = () => {
const candidates = [1, 2, 3, 4, 5, 6, 7, 8, 9];
const array = [];
for (let i = 0; i < 4; i++) {
const chosen = candidates.splice(Math.floor(Math.random() * (9 - i)), 1)[0];
array.push(chosen);
}
return array;
};
export default {
data() {
return {
answer: getNumbers(),
tries: [],
inputValue: '',
result: '',
};
},
methods: {
onSubmitForm() {
if (this.inputValue === this.answer.join('')) {
this.tries.push({
try: this.inputValue,
result: '홈런',
});
this.result = '홈런';
alert('게임을 다시 실행합니다');
this.inputValue = '';
this.answer = getNumbers();
this.tries = [];
this.$refs.focusInputbox.focus();
} else {
if (this.tries.length >= 9) {
this.result = `10번 넘게 틀려서 실패! 답은 ${this.answer.join(',')} 였습니다`;
alert('실패! 게임을 다시 시작합니다');
this.inputValue = '';
this.answer = getNumbers();
this.tries = [];
this.$refs.focusInputbox.focus();
}
let strike = 0;
let ball = 0;
const answerArray = this.inputValue.split('').map((number) => parseInt(number));
for (let i = 0; i < 4; i++) {
if (answerArray[i] === this.answer[i]) {
strike++;
} else if (this.answer.includes(answerArray[i])) {
ball++;
}
}
this.tries.push({
try: this.inputValue,
result: `${strike} 스트라이크, ${ball} 볼입니다`,
});
this.inputValue = '';
this.$refs.focusInputbox.focus();
}
},
},
};
</script>
<style>
</style>