独立JS游戏帮助:如何将用户输入转换为对象?

时间:2015-01-15 14:47:42

标签: javascript

我想提一下,我还在努力将JS与HTML和CSS配对。     我只是制作一个独立的JS控制台游戏,以便更熟悉语法。     我的想法是让这个人通过"提示"并能够列出它们。到目前为止,我已经完成了对#34;处理提示"点。     我需要帮助弄清楚如何让用户给出一个名字"田地和"年龄"字段并将其推入一个数组,我将创建一个列表函数来搜索并列出他们在该会话中创建的所有人员(我不知道如何使用cookie来完成这样的事情。)

到目前为止,我已经尝试在询问姓名和年龄时直接在提示框中输入name, age,但它会将姓名和年龄保存到姓名'数组中的项而不是对象。

TL; DR - 我需要将用户输入转换为对象并将所述对象推送到数组中。

//We name the functions.
function Person(name, personAge) {
    this.name = name
    this.personAge = personAge
}

function Animal(animalName, species, breed) {
    this.animalName = animalName
    this.species = species
    this.breed = breed
}

function CreateYourOwn(creativeName, species, power, customAge) {
    this.creativeName = creativeName
    this.species = name
    this.power = power
    this.customAge = customAge
}

//We list the arrays.
var Persons = [


    ]

var Animals = [



    ]

var Customs = [


    ]

//I start the prompt to ask the user which one.
var personPrompt = prompt("Welcome to virtual reality! Put in 'person' for person creator, 'animal' for animal creator, and 'custom' for custom creator!").toLowerCase()


//And this is where I am right now.
switch(personPrompt) {
    case 'person':
        var personCreator = prompt("Put in (name, age) in exactly that form").replace(/['"]/g,'');
        this.name = name
        this.age = age
        personCreator = new Person(name, age)
        break;
}

2 个答案:

答案 0 :(得分:0)

示例:http://jsfiddle.net/oL9dwbp6/

case 'person':
    var personPromtResult = prompt("Put in (name, age) in exactly that form").replace(/['"]/g,'');
    var personPromtResultArray = personPromtResult.split(',');
    if(personPromtResultArray.length!=2){
        alert('Incorrect input!');
        break;
    }
    var name = personPromtResultArray[0];
    var age = parseInt(personPromtResultArray[1]);
    if(isNaN(age)){
        alert('Incorrect age!');
        break;
    }
    var person = new Person(name, age)
    console.log(person);
    break;

答案 1 :(得分:0)

你的交换机中有一些问题,我用一些评论重写了这个问题:

switch(personPrompt) {
    case 'person':
        //collecting name
        var name = prompt("Name:").replace(/['"]/g,'');
        //collecting age
        var age = prompt("Age:").replace(/['"]/g,'');
        //creating an instance of person
        var person = new Person(name, age);
        //adding person to Persons array
        Persons.push(person);
        break;
}

//and then you can access person that you just created like Persons[0]

JsFiddle