简体   繁体   English

Javascript函数显示用户输入数组

[英]Javascript- function displaying user input array

I'm working on a JavaScript short program (trampoline hiring), the purpose of the program is to record according to the name of each customer currently on the trampoline and whether they are an adult or a child (status type). 我正在开发JavaScript简短程序(雇用蹦床),该程序的目的是根据当前在蹦床上的每个客户的姓名以及他们是成人还是儿童(状态类型)进行记录。

Currently I have addcustomer , displayallcustomer and deletelastcustomer functions, however I am not sure what I have done wrong for the displayCustomerType(statusType) function. 当前,我有addcustomerdisplayallcustomerdeletelastcustomer函数,但是我不确定displayCustomerType(statusType)函数做错了什么。 This function is for when I press Display Only Child Customers or Display Only Adult Customers , it will only display child or adult from the array list. 当我按“仅显示儿童客户”“仅显示成人客户”时 ,此功能仅在阵列列表中显示儿童或成人。

Demo on Fiddle 小提琴演示

 <html> <head> <meta charset="utf-8" /> <title>work 2</title> <script type="text/javascript"> //maximum customer on the trampoline is 5 const MAX_CUSTOMERS = 5; //create new Array var customerList = new Array(); //add customer function addCustomer() { //check max customers if (customerList.length >= MAX_CUSTOMERS) { alert('Sorry, no more than ' + String(MAX_CUSTOMERS) + ' customers are allowed on the trampoline.'); } else { //add new user var newIndex = customerList.length; customerList[newIndex] = new Object; //ask user enter their name customerList[newIndex].name = prompt('What is the customer\\'s name?'); //ask user enter their status customerList[newIndex].status = prompt('Are you a Child or an Adult?'); //check user is child or adult while (!(customerList[newIndex].status == 'child' || customerList[newIndex].status == 'adult')) { customerList[newIndex].status = ( prompt('Error Please Enter \\'child\\' or \\'adult\\':')); } } } //display customers function displayAllCustomers() { //create message var message = ''; //loop customers for (var i = 0; i < customerList.length; i++) { //add customer to message message += customerList[i].name + ', Status: ' + String(customerList[i].status) + '. \\n'; } //check message if (message == '') { message = 'There are no customer to display!'; } //output message alert(message); } //delete last customer function deleteLastCustomer() { //check customer list if (customerList.length > 0) { //delete last customer customerList.length--; alert('The last customer has been deleted.'); } else { alert('There are no customer to delete!'); } } function displayCustomerType(statusType) { var message = ''; for (var i = 0; i < customerList.length; i++) { //loop through customerlist message += customerList[i].status + '. '; } if ((customerList[i].status = 'child') || (customerList[i].status = 'adult')) { alert(message); } } </script> </head> <body> <div> <button type="button" onclick="addCustomer();">Add Customer</button> <br> <button type="button" onclick="displayAllCustomers();">Display All Customers</button> <br> <button type="button" onclick="deleteLastCustomer();">Delete Last Customer</button> <br> <button type="button" onclick="displayCustomerType('child');">Display Only Child Customers</button> <br> <button type="button" onclick="displayCustomerType('adult');">Display Only Adult Customers</button> <br> </div> </body> </html> 

There are two points here. 这里有两点。

  1. You should use good function names. 您应该使用好的函数名称。
  2. You must understand what you want your code to do. 您必须了解您希望代码执行的操作。

1. Use good function names. 1.使用好的函数名称。

Your function is named displayCustomerType() . 您的函数名为displayCustomerType() It accepts one argument. 它接受一个论点。 If I was to guess the purpose of the displayCustomerType(arg) function does, I would suppose that it displays the type of a customer object which is provided as an argument. 如果我猜想displayCustomerType(arg)函数的作用是,我假设它显示了作为参数提供的客户对象的类型。 Therefore, if I provided it with a customer of the "child" type, I might expect it to display the type "child." 因此,如果我向其提供“子”类型的客户,则可能希望它显示“子”类型。

If I'm correct, this is not what you want to happen. 如果我是正确的话,那不是您想要发生的事情。 Your button is named "Display All Child Customers." 您的按钮名为“显示所有子客户”。 Therefore, I assume that you would prefer to provide the function with a customer type and then display all customers from your list of customers which have that type. 因此,我假设您希望为该功能提供一个客户类型,然后显示具有该类型的客户列表中的所有客户。

Addressing this problem is simple. 解决这个问题很简单。 Use good function names. 使用好的函数名称。 displayCustomersOfType(arg) would do. displayCustomersOfType(arg)可以。 Using a function name like that would make it clearer to people who are using your code that your code functions in a certain way. 使用这样的函数名称可以使使用代码的人更清楚地知道您的代码以某种方式起作用。

2. Understand what you want your code to do. 2.了解您想要代码做什么。

Maybe you think you know what you want your code to do. 也许您认为您知道自己想要代码做什么。 You have it in your head. 你有它的头。 You asked in a comment, "Why is it showing 'child, child, child'?" 您在评论中问:“为什么显示'孩子,孩子,孩子'?” I'll tell you why. 我告诉你为什么。 It's displaying that because that's what you told it to display. 它之所以显示是因为您告诉它要显示的内容。 Let's break down what this displayCustomersOfType(arg) function should do. 让我们分解一下displayCustomersOfType(arg)函数应该做什么。

  1. Accept an argument. 接受一个论点。
  2. Use the argument to filter the number of customers being displayed. 使用参数过滤显示的客户数量。
  3. Display all of the customers which pass the filter. 显示所有通过过滤器的客户。

Then we can start thinking about how this should work in code. 然后,我们可以开始考虑如何在代码中工作。 We have an array of customer objects. 我们有一系列客户对象。 Each one has a status and a name among other things. 每个人都有一个状态和一个名字。 You want to call on this function, provide it with an customer type argument, filter the list of customers with that argument, and display the customers which pass the filter. 您要调用此函数,为它提供一个客户类型参数,使用该参数过滤客户列表,并显示通过过滤器的客户。 Let's start figuring out how that can be coded. 让我们开始弄清楚该如何编码。

  1. Create a function displayCustomersOfType(arg) 创建一个函数 displayCustomersOfType(arg)
  2. For each customer in the list of customers, 对于客户列表中的每个客户,
  3. If the customer's type is equal to the specified type, 如果客户的类型 等于指定的类型,
  4. Append that customer's name to the output. 将该客户的名称 附加到输出中。
  5. Display the output. 显示输出。

Each of these is a logical step in the process. 这些都是过程中的逻辑步骤。 Being able to interpret abstract requirements like the first set of steps and understand them in terms of logical steps like the second set of steps is an absolutely vital skill for a software developer. 对于软件开发人员来说,能够像第一组步骤那样解释抽象需求并像第二组步骤一样在逻辑步骤方面理解它们是绝对重要的技能。 I suspect that you want to become a software developer because you have software development homework. 我怀疑您想成为软件开发人员,因为您有软件开发作业。 If I'm correct, then you need to develop this skill. 如果我是正确的,那么您需要发展这项技能。

Let's look at an example. 让我们看一个例子。

I have some fruit. 我有水果。 There are two apples, a banana, and two cherries. 有两个苹果,一个香蕉和两个樱桃。 I want to write a function which will only show those fruits that have a particular name. 我想编写一个仅显示具有特定名称的水果的函数。 For each fruit in my list of fruits, I'll add the fruit to the message if it has the name that I specify. 对于水果列表中的每个水果,如果它具有我指定的名称,则将其添加到消息中。 Then I'll display the list of fruit with that name. 然后,我将显示具有该名称的水果列表。

JSFiddle: http://jsfiddle.net/kLur4qc5/ JSFiddle: http : //jsfiddle.net/kLur4qc5/

var fruits = ['apple', 'apple', 'banana', 'cherry', 'cherry'],
    showFruitsWithName = function (name) {
        var message = "";
        fruits.forEach(function (fruit) {
            if (fruit === name) {
                message += name + " ";
            }
        });
        alert(message);
    };

showFruitsWithName('cherry');

There is an answer here. 这里有一个答案。 It's written in the five step list. 它写在五个步骤列表中。 I even bolded some keywords for you. 我什至为您加粗了一些关键字。 I have faith that you can make sense of the example code and apply it to your purpose. 我相信您可以理解示例代码并将其应用于您的目的。 You can figure this out. 您可以找出答案。

Ask questions. 问问题。 I'll answer them, but try to make them specific questions. 我会回答他们,但尝试使他们有特定的问题。 Don't ask "How do I do this? Please provide complete code examples that I can copy and paste." 不要问“我该怎么做?请提供可复制和粘贴的完整代码示例”。 I know that it's tempting to do that especially since you get answers pretty quickly that way, but you're only hurting yourself if you don't truly understand this stuff. 我知道这样做是很诱人的,特别是因为这样您很快就能得到答案,但是如果您不真正了解这些内容,只会伤害自己。

Changed your entire code and now it works. 更改了整个代码,现在可以使用了。

Demo on Fiddle 小提琴演示

HTML: HTML:

<body>
    <div>
        <label>Name: </label><input type="text" id="name" />
        <br />
        <label>Adult/Child: </label><input type="text" id="status" />
        <br />
        <br />
        <button>Add Customer</button>
        <br />
        <button>Display All Customers</button>
        <br />
        <button>Delete Last Customer</button>
        <br />
        <button id="Child">Display Only Child Customers</button>
        <br />
        <button id="Adult">Display Only Adult Customers</button>
        <br />
    </div>
    <br />
    <br />
    <div id="message"></div>
</body>

JavaScript: JavaScript:

var buttons = document.getElementsByTagName('button');
var m = document.getElementById('message');
var maxCustomers = 5;
var customerList = [];

buttons[0].onclick = function addCustomer() {
    if (customerList.length >= maxCustomers) {
        m.innerHTML = 'Sorry, no more than ' + maxCustomers + ' customers are allowed on the trampoline.';
    } else {
        var n = document.getElementById('name').value;
        var s = document.getElementById('status').value.toLowerCase();
        if (!n && !s) m.innerHTML = 'Please fill the input boxes first!';
        customerList.push({
            name: n,
            status: s.slice(0, 1).replace(s.slice(0, 1), s.slice(0, 1).toUpperCase()) + s.slice(1, s.length)
        });
        m.innerHTML = n + ' has been added to the List.'
    }
};

buttons[1].onclick = function displayAllCustomers() {
    var message = '';
    for (var i = 0; i < customerList.length; i++) {
        message += 'Name: ' + customerList[i].name + ', Adult/Child: ' + customerList[i].status + '. <br />';
    }
    if (message === '') {
        message = 'There are no customer to display!';
    }
    m.innerHTML = message;
};

buttons[2].onclick = function deleteLastCustomer() {
    if (customerList.length > 0) {
        customerList.length--;
        m.innerHTML = 'The last customer has been deleted.';
    } else {
        m.innerHTML = 'There are no customer to delete!';
    }
};

buttons[3].onclick = buttons[4].onclick = function displayCustomerType() {
    var message = '';
    for (var i = 0; i < customerList.length; i++) {
        if (customerList[i].status == this.id) {
            message += 'Name: ' + customerList[i].name + ', Adult/Child: ' + customerList[i].status + '. <br />';
        }
    }
    if (message === '') {
        message += 'None Found!';
    }
    m.innerHTML = message;
};

Your curly brackets are a little off scope. 大括号有点超出范围。 It should be more like: 应该更像是:

var message = '';
for (var i = 0; i < customerList.length; i++) {
    if (customerList[i].status === statusType) message += customerList[i].status + '. ' ;
}
alert(message);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM