【问题标题】:How to pass a prompt as an object/function parameter如何将提示作为对象/函数参数传递
【发布时间】:2014-04-30 19:04:34
【问题描述】:

在 Java 中,我可以从提示创建变量,然后使用非默认对象构造函数并将这些提示变量作为参数传入,以创建该对象的新实例。 javaScript中是否有与此等价的功能?

Java 示例:

    String first = JOptionPane.showInputDialog("What is your first name?");
    String last = JOptionPane.showInputDialog("What is your last name?");
    String gender = JOptionPane.showInputDialog("What gender are you? Male of Female?");
    int month = Integer.parseInt(JOptionPane.showInputDialog("Enter the two digits of your birth month"));
    int day = Integer.parseInt(JOptionPane.showInputDialog("Enter the two digits of your birth day"));
    int year = Integer.parseInt(JOptionPane.showInputDialog("Enter the four digits of your birth year"));

    //I have this non-default constructor created in another Class
    HealthProfile health1 = new HealthProfile(first, last, gender, month, day, year); 

我已经在 J​​S 中尝试了几种不同的方法,但完全可以做到。我是两种语言的初学者,所以请耐心等待。

在 javaScript 中尝试破解作业:

var firstName = prompt("enter your first name");
var lastName = prompt("enter your last name");
var gender = prompt("enter your gender");
var birthMonth = prompt("enter the two digits of your birth month");
var birthDay = prompt("enter the two digits of your birth day");
var birthYear = prompt("enter the four digits of your birth year");

  function person(firstName, lastName, gender, birthMonth, birthDay, birthYear){
    this.firstName = {};
    this.firstName = firstName;
    this.lastName = lastName;
    this.birthMonth = birthMonth;
    this.birthDay = birthDay;
    this.birthYear = birthYear;
}

就像我说的,我用了几种不同的方法都没有成功。这只是我最近的尝试。

【问题讨论】:

  • 你给new person(firstName,lastName....)打过电话吗?
  • 不,先生,我没有!哈哈...谢谢!

标签: javascript object function-parameter


【解决方案1】:

这行得通:

var firstName = prompt("enter your first name");
var lastName = prompt("enter your last name");
var gender = prompt("enter your gender");
var birthMonth = prompt("enter the two digits of your birth month");
var birthDay = prompt("enter the two digits of your birth day");
var birthYear = prompt("enter the four digits of your birth year");

function person(firstName, lastName, gender, birthMonth, birthDay, birthYear){
   return {
       firstName: firstName,
       lastName: lastName,
       birthMonth: birthMonth,
       birthDay: birthDay,
       birthYear: birthYear
   };
}

var test = person(firstName, lastName, gender, birthMonth, birthDay, birthYear);

【讨论】:

    【解决方案2】:

    答案是肯定的。可以在 javaScript 中创建一个函数,该函数可以作为 Java 中的非默认构造函数。您可以提示用户提供信息,为他们的响应分配一个变量,然后将该变量作为参数传递给您的函数。

    在我上面的代码中,我只是忽略了实例化一个新的 Person 对象。

    感谢大家的帮助!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-02-23
      • 2012-05-30
      • 1970-01-01
      • 1970-01-01
      • 2019-10-19
      • 1970-01-01
      • 2021-04-15
      相关资源
      最近更新 更多