将用户输入从 javascript 中的提示转换为数组,然后将其推送到对象上

Converting user input from prompts in javascript into an array and then pushing it onto an object

本文关键字:然后 对象 数组 输入 用户 javascript 提示 转换      更新时间:2023-09-26

我想以提示的形式获取用户的输入并将其转换为数组,以便我可以将其推送到先前创建的对象上

这是我的代码(脚本):

     var addperson = prompt("Would you like to add someone yes or no?( you must type 'yes' in this exact way)")
        if(addperson == "yes" ){
                var firstName = prompt("What is this person's first name?");
                var lastName = prompt("What is this person's last name?");
                var age = prompt("How old is this person?");
                var email = prompt("What is their email adress?");
                    if(!/^[@]+$/.test(email) || !email){
                    alert("Your email is valid");
                    }else{
                        alert("You did not give a valid email please re-type it, and make sure you include the @ symbol");
                        email;
                    }

            function newPeople(){
                var newPerson = [ firstName, lastName, age, email ];
                var something = [];
                for(var i=0; i<newPerson.length; i++){
                    var data2 = newPerson[i].split(';');
                        var lines2 = [];
                        for(var j=0; j<data2.length; j++){
                            lines2.push(data2[j]);
                        }
                        something.push(lines2);
                }
            something.push(lines);  
            }       
        }  
    console.log(lines); 

您可以使用 .push 直接将新对象推送到数组中。检查此工作示例。

然后,添加的对象将按以下格式打印到控制台上:

Age: "234"
Email: "d@d."
FirstName: "jh"
LastName: "j"