scythercas
@scythercas

Are you sure you want to delete the question?

Leaving a resolved question undeleted may help others!

取得した文字列に一致するポケモンのobjectを呼び出したい

コード内のコメントにもありますが、ボタンが押されたら、selectで選択された文字列と名前が一致するポケモンobjectが持つ関数displayStatusを呼び出し、種族値を表示することが目標です。

おそらく変数enteredNameに格納された文字列を変数に変換していない(?)ことが問題点だと思うのですが、解決策がわかりません。

if(enteredName=="gaburiasu"){
   gaburiasu.displayStatus;
}else if(...){
   ...;
}else if(...){
....

のようにすることで出来なくはないと考えましたが、ポケモンの数を増やしていくことを考えると現実的でないため、効率的な方法を知りたいです。

拙い日本語ですみません。
どなたかご教授願います。

<!DOCTYPE html>
<html lang="ja">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>種族値保管庫</title>
</head>
<body>
    <select id="inputName">
        <option value="gaburiasu">ガブリアス</option>
        <option value="ahgoyon">アーゴヨン</option>
        <option value="tekkaguya">テッカグヤ</option>
    </select>
    <button id="submit">種族値を表示</button>
<script>
    function pokemon(name, mainType, subType, baseStatus){
        this.name = name,
        this.type = [mainType, subType],
        this.baseStatus = baseStatus,
        this.displayStatus = function(){
            console.log(this.baseStatus);
        }
    }
    function baseStatus(h,a,b,c,d,s){
        this.hitPoint = h,
        this.attack = a,
        this.defense = b,
        this.spacialAttack = c,
        this.specialDefence = d,
        this.speed = s
    }

    document.getElementById("submit").addEventListener("click",()=>{
        //ボタンがクリックされたら、選択されたポケモンのdisplayStatus関数が呼び出されるようにしたい。
        let enteredName = document.getElementById("inputName").value;
        enteredName.displayStatus;
    },false);

    let sGaburiasu = new baseStatus(108, 130, 95, 80, 85, 102);
    let gaburiasu = new pokemon("ガブリアス", "ドラゴン", "じめん", sGaburiasu);

    let sAhgoyon = new baseStatus(73, 73, 73, 127, 73, 121);
    let ahgoyon = new pokemon("アーゴヨン", "どく", "ドラゴン", sAhgoyon);
    
    let sTekkaguya = new baseStatus(97, 101, 103, 107, 101, 61);
    let tekkaguya = new pokemon("テッカグヤ", "はがね", "ひこう", sTekkaguya);
</script>
</body>
</html>
0

1Answer

Mapなどで文字列とポケモンを対応させると良いのではないかと思います。

const pokemons = new Map([
  ["gaburiasu", new Pokemon(...)],
  ...
]);

const pokemon = pokemons.get("gaburiasu");
if (pokemon) {
  pokemon.displayStatus(); // 関数の呼び出しは`()`が必要
}

2Like

Comments

  1. @scythercas

    Questioner

    @woxtu さん
    無事やりたかったことができました。ご回答ありがとうございます!!

Your answer might help someone💌