Javascript程序 - 从数组中删除元素

时间:2014-11-06 23:41:39

标签: javascript arrays

我写的节目是关于运动器材公司如何监控蹦床的使用情况;它记录了客户NAME,以及他们目前在蹦床上的状态(儿童或成人)。有五个功能,因此我们可以添加客户,显示客户并删除最后一个客户。我被困在最后一个函数上,我必须使用对象构造函数来识别并删除客户。

PS :我无法使用任何预定义的JavaScript数组元素 - 删除或操纵delete()concat()join(),{{1}等方法},pop()

push()

2 个答案:

答案 0 :(得分:0)

您可以返回一个新阵列。

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/

编辑: 添加评论以澄清。那个更好吗?我们的想法是,您可以通过创建一个新的水果数组,添加所有不是已删除水果的水果,并返回该新数组来重新创建splice()方法的功能。

在这种情况下,我们deleteFruit('apple')。因此,我们循环通过水果列表(苹果,香蕉,胡萝卜)。对于每种水果,如果它不是苹果,我们将其添加到新的水果中。这意味着我们的新系列水果含有香蕉和胡萝卜。该函数返回新的水果数组,并将其分配给旧的水果数组。

如果你从三个水果开始,然后你最终得到两个水果,你就删除了一个。您不必使用splice()。事实上,如果像splice()这样的函数以类似的方式执行它们的功能,我不会感到惊讶,尽管发明splice()的人肯定比我做得更好。

我希望这会有所帮助。

P.S。胡萝卜现在是一种水果。 :)

答案 1 :(得分:0)

<强>解决方案

//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;
}

如上所述,您可以找到解决方案,正如Brandon所说,已经创建了一个新阵列,其中每个客户都添加如果此客户不是那么您正在寻找。因此,为您留下一个阵列没有您正在寻找的客户,这个新阵列将替换您原来的阵列。