0

私はJavaScriptを学ぼうとしているので、練習のためにこのプロジェクトをやっています。オブジェクトとそのすべてがどのように機能するかを理解しようとしています。基本的に私が欲しいのは、それぞれに特定のプロパティが割り当てられた、オブジェクトとしての人々のリストです。次に、あなたが考えている人を推測するまで、たくさんの質問をします. 私は周りを検索しましたが、これを行う方法を正確に見つけることができません。これは私がこれまでに持っているものです:

function person(name,age,eyecolor,gender,eyeglasses)
{
    this.name=name;
    this.age=age;
    this.eyecolor=eyecolor;
    this.gender=gender;
    this.eyeglasses=eyeglasses;
}

var Dad=new person("Dad",45,"blue","male",true);
var Mom=new person("Mom",48,"blue","female",false);
var Brother=new person("Brother",16,"blue","male",false);
var Sister=new person("Sister",15,"green","female",false);

function askQuestion (){

}

function begin(){
    askQuestion();
}

今私が欲しいのは、askQuestion関数で、その人についてこれまでに知っていることに基づいてリストから質問を選択できる方法です。そして、それが誰であるかを再計算し、別の質問を選んで、それが誰であるかがわかるまで. うまくいけば、私はこれを明確にしました。どうすればいいですか?

4

2 に答える 2

1

これが私がそれを行う方法です。Aaditの回答よりも短く、私の意見では、よりシンプルで理解しやすい.

人々のリストを作成します。配列リテラルを使用します。

var people = [Dad, Mom, Brother, Sister];

私は自分のコードを構造化するのが好きなので、質問をオブジェクトに入れます:

var questions = {
    "Are they male or female?" : 'gender',
    "What is their eye color?" : 'eyecolor',
    "Do they wear glasses?" : 'eyeglasses'
};

これは、必要な数のプロパティで拡張できます。

それで:

for (question in questions) { //This is how you loop through an object
    var property = questions[question]; //This gets the second part of the object property, e.g. 'gender'
    var answer = prompt(question);

    //filter is an array method that removes items from the array when the function returns false.
    //Object properties can be referenced with square brackets rather than periods. This means that it can work when the property name (such as 'gender') is saved as a string.

    people = people.filter(function(person) { return person[property] == answer });

    if (people.length == 1) {
        alert("The person you are thinking of is " + people[0].name);
        break;
    }
    if (people.length == 0) {
        alert("There are no more people in the list :(");
        break;
    }
}

そして、私もあなたをフィドルにしました。ここにあります。

于 2013-04-21T18:24:55.000 に答える