0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

JavaScriptでじゃんけん判定、ミスった…でも解決した話 set と .has()

Last updated at Posted at 2025-02-24

「じゃんけん? 余裕でしょ!」と思って書いたコードが、全然動かない…。よくある問題だからこそ、うっかりミスしがち。僕も lines.length の使い方を間違えてハマったのと、もっとスッキリしたコード書けるのに始めは知らなかった。気づいたことを共有するよ!


NGコードでは、lines.length をそのままループに使ったけど、実際には lines[0] に試合数が入っていた…。さらに、勝ちパターンの判定を if 文でゴリゴリ書いていて、もっとスッキリ書ける方法があった。

改善前(ゴリゴリ if 文)

if (lines[count] == "G C" ) {
    win++;
} else if (lines[count] == "C P") {
    win++;
} else if (lines[count] == "P G") {
    win++;
}

このままだと、勝ちパターンが増えたときに else if の嵐になってしまう…。
改善後(Set でスッキリ!)

const winPatterns = new Set(["G C", "C P", "P G"]);  
for (let count = 1; count <= Number(lines[0]); count++) {  
    if (winPatterns.has(lines[count])) win++;  
}

Set を使えば、if 文の連続が消えて、勝ちパターンの管理も楽になる!
Set とは?

Set は、重複を許さないデータを管理する便利なオブジェクト。配列と違って .has() メソッドで値の存在チェックが簡単にできる!

const winPatterns = new Set(["G C", "C P", "P G"]);  
console.log(winPatterns.has("G C")); // true  
console.log(winPatterns.has("P P")); // false  

僕の失敗談と解決話→ Paizaで基本マスター

0
0
3

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?