简体   繁体   中英

Javascript program - deleting an element from an array

The program I wrote is about how a sports equipment company monitor the trampoline use; it records the customer NAME, and their STATUS (child or adult) that are currently on the trampoline. There are five functions, so we can add customer, display customer and delete the last customer. I am stuck on the last function where I have to use object constructor to identify and then delete the customer.

PS : I can't use any predefined JavaScript array element-deleting or manipulating methods such as delete() , concat() , join() , pop() , push()

const MAX_CUSTOMERS = 5; //maximum customer on the trampoline is 5

var customerList = new Array();//create new Array

function addCustomer () 
{
     if (customerList.length >= MAX_CUSTOMERS)
        alert('Sorry, no more than ' + String(MAX_CUSTOMERS) + ' customers are allowed on the trampoline.')
     else
    {
        var newIndex = customerList.length; 
        customerList[newIndex]  = new Object;
        customerList[newIndex].name = prompt('What is the customer\'s name?'); //ask user enter their name
        customerList[newIndex].status = prompt('Are you a Child or an Adult?'); //ask user enter their status      
        while (!(customerList[newIndex].status == 'child' || customerList[newIndex].status == 'adult'))
        {
            customerList[newIndex].status = (prompt('Error Please Enter \'child\' or \'adult\':'));
        }       

    }
}

function displayAllCustomers () 
{
    var message = '';
    for (var i = 0 ; i < customerList.length ; i++) 
    {
        message += customerList[i].name + ', Status: ' 
                    + String(customerList[i].status) + '. \n'; 
    }
    if (message == '')
        message = 'There are no customer to display!';
    alert(message);

}

function deleteLastCustomer () 
{
    if (customerList.length > 0)
    {
        customerList.length--;
        alert('The last customer has been deleted.');
    }
    else
        alert('There are no customer to delete!');             
}


function identifyThenDeleteCustomer ()
{
    var customerName = prompt('Enter the name of the customer to delete:');
    var customerStatus = prompt('Enter \'child\' or \'adult\':');
    while (!(customerStatus == 'child' || customerStatus == 'adult'))
        customerStatus = prompt('Error - enter \'child\' or \'adult\':');
    deleteCustomer(customerName,customerStatus);    
}

function deleteCustomer (aName, aStatus)
{
    ;               
} 

You could return a new array.

var fruits = ['apple', 'banana', 'carrot'],     // This is an array of fruits.
    deleteFruit = function (name) {             // A name of a fruit is an argument.
        var i = 0,
            newFruits = [];

        fruits.forEach(function (fruit) {       // It cycles through the list of fruits.
            if (fruit !== name) {               // If the current fruit is not the argument,
                newFruits[i] = fruit;           // add the fruit to a new array of fruits.
                i++;
            }
        });

        return newFruits;                       // Return the new array of fruits.
    },
    printFruits = function () {
        fruits.forEach(function (fruit) {
            alert(fruit);
        });
    },
    exec = function () {
        fruits = deleteFruit('apple');          // Set the old array equal to the returned array.
    };

exec();
printFruits();

JSFiddle: http://jsfiddle.net/Lf2e85ed/3/

Edit: Added comments to clarify. Is that better? The idea is that you can recreate the functionality of a splice() method by creating a new array of fruits, adding all of the fruit which are not the deleted fruit, and returning that new array.

In this case, we deleteFruit('apple'). Therefore, we cycle through the list of fruits (apple, banana, carrot). For each fruit, if it is not an apple, we add it to the new array of fruits. That means our new array of fruits contains banana and carrot. The function returns the new array of fruits, and it's assigned to the old array of fruits.

If you start with three fruits, and then you end up with two fruits, you've deleted one. You don't have to use splice(). In fact, it wouldn't surprise me if functions like splice() perform their functionality in a way similar to this, though the people who invented splice() surely did a better job than I did.

I hope this helps.

PS A carrot is a fruit now. :)

Solution

//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!');
    }
}

//identify then delete customer
function identifyThenDeleteCustomer() {
    //get customer name
    var customerName = prompt('Enter the name of the customer to delete:');

    //get customer status
    var customerStatus = prompt('Enter \'child\' or \'adult\':');

    //check customer status
    while (!(customerStatus == 'child' || customerStatus == 'adult')) {
        customerStatus = prompt('Error - enter \'child\' or \'adult\':');
    }

    //delete customer
    deleteCustomer(customerName, customerStatus);
}

//delete customer
function deleteCustomer(aName, aStatus) {
    //create new array
    var newCustomerList = new Array();

    //loop customers
    for (var i = 0; i < customerList.length; i++) {
        var customer = customerList[i];

        //check customer
        if ((customer.name != aName) || (customer.status != aStatus)) {
            //add new user
            var newIndex = newCustomerList.length;
            newCustomerList[newIndex] = customer;
        }
    }

    //check deleted
    if (newCustomerList.length < customerList.length) {
        alert('The customer has been deleted.');
    } else {
        alert('There are no customer to delete!');
    }

    //update customer list
    customerList = newCustomerList;
}

So above you can find the solution, as Brandon mentioned, a new array has been created, in which each customer was added if this customer was not the one you were looking for. Therefore leaving you with an array without the customer you were looking for, this new array then replaces your original one.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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