简体   繁体   English

从JavaScript数组添加和删除值

[英]Adding and Removing Values from JavaScript Array

I have a JavaScript array of numbers. 我有一个JavaScript数字数组。 My array is defined like this: 我的数组是这样定义的:

var customerIds = [];

I have a function that is responsible for inserting and removing ids to/from this array. 我有一个函数,负责向此数组中插入和删除ID。 Basically, my function looks like this: 基本上,我的函数如下所示:

function addOrRemove(shouldAdd, customerId) {
  if (shouldAdd) {
    if (customerIds.contains(customerId) === false) {
      customerIds.push(customerId);
    }
  } else {
    customerIds.remove(customerId);
  }
}

This function is basically pseudocode. 此功能基本上是伪代码。 A JavaScript array does not have a contains or remove function. JavaScript数组没有包含或删除功能。 My question is, is there any elegant way of tackling this problem? 我的问题是,有没有解决此问题的优雅方法? The best I can come up with is always looping through the array myself and tracking the index of the first item found. 我能想到的最好的办法就是总是自己遍历数组并跟踪找到的第一项的索引。

Thank you for any insights you can provide. 感谢您提供的任何见解。

  1. The contains can be achieved with Array.prototype.indexOf , like this contains可实现Array.prototype.indexOf ,像这样

     if (customerIds.indexOf(customerId) === -1) { 

    indexOf function returns -1 , if it couldn't find the parameter in the array, otherwise the first index of the match. 如果在数组中找不到参数, indexOf函数将返回-1 ,否则返回匹配项的第一个索引。 So, if the result is -1 , it means that customerIds doesn't contain customerId . 因此,如果结果为-1 ,则表示customerIds 不包含 customerId

  2. The remove can be achieved with Array.prototype.indexOf and Array.prototype.splice , like this 可以使用Array.prototype.indexOfArray.prototype.splice实现remove ,就像这样

     var index = customerIds.indexOf(customerId); if (index !== -1) { customerIds.splice(index, 1); } 

    Similarly, indexOf function returns -1 , if it couldn't find the parameter in the array, otherwise the first index of the match. 同样,如果在数组中找不到参数, indexOf函数将返回-1 ,否则返回匹配项的第一个索引。 So, if the result is -1 , we skip deleteing, otherwise splice 1 element starting from the position index . 因此,如果结果为-1 ,则跳过删除,否则从position index开始splice 1元素。

Use indexOf and splice 使用indexOfsplice

function addOrRemove(shouldAdd, customerId) {
    if (shouldAdd) {
        if (customerIds.indexOf(customerId) == -1) {
            customerIds.push(customerId);
        }
    } else {
        var index = customerIds.indexOf(customerId)
        customerIds.splice(index, 1);
    }
}

You can extend the Array method like below after that you are free to use 'contains' and 'remove' 在可以自由使用“包含”和“删除”之后,可以像下面那样扩展Array方法。

if (!Array.contains)
    Array.prototype.contains = function(a) {
        for (var i in this) {
            if (this[i] == a) return true;
        }
        return false
    }
if (!Array.remove)
    Array.prototype.remove = function(a) {
        for (var i in this) {
            if (this[i] == a) {
                this.splice(i, 1);
            }
        }
    }

You could definitely use the splice and indexOf as stated by @thefourtheye, yet I would like to provide another approach. 您绝对可以使用@thefourtheye所述的spliceindexOf ,但我想提供另一种方法。

Instead of using an array you could use an object . 除了使用array还可以使用object

var customerIds = {};
//This could also be stated as: var customerIds = new Object(); this is just shorthand

function addOrRemove(shouldAdd, customerId)
{
    if(shouldAd)
    {
        if(!customerIds[customerId])
        {
            customerIds[customerId] = new Object();
            customerIds[customerId].enabled = true;
        }
    }
    else
    {
        if(customerIds[customerId])
        {
            customerIds[customerId].enabled = false;
        }
    }
}

You now can query against the customerIds object for a specific customerId 现在,您可以查询customerIds对象以获取特定的customerId

if(customerIds[customerId].enabled)

Using this method not only provides you with the capability of attaching multiple attributes to a given customerId , but also allows you to keep records of all customerIds after disabling (removing). 使用此方法不仅为您提供了将多个属性附加到给定的customerId ,而且还允许您在禁用(删除)后保留所有customerIds记录。

Unfortunately, in order to truely remove the customerId , you would need to loop through the object and append each property of the object to a new object except for the one you do not want. 不幸的是,为了真正删除customerId ,您将需要遍历该对象并将该对象的每个属性附加到一个新对象,除了不需要的对象之外。 The function would look like this: 该函数将如下所示:

function removeId(customerId)
{
    var n_customerIds = new Object();

    for(var key in customerIds)
    {
        if(key != customerId)
        {
            n_customerIds[key] = customerIds[key];
        }
    }

    customerIds = n_customerIds;
}

In no way am I stating that this would be the proper approach for your implementation, but I am just providing another method of achieving your goal. 我绝不是说这将是实现您的正确方法,但我只是提供了另一种实现目标的方法。 There are many equivalent ways to solve your dilemma, and it is solely decided by you which method will best suit your projects functionality. 有许多等效的方法可以解决您的难题,并且完全由您决定哪种方法最适合您的项目功能。 I have personally used this method in many projects, as well as I have used the methods posted by others in many other projects. 我已经在许多项目中亲自使用了此方法,并且在许多其他项目中也使用了其他人发布的方法。 Each method has their pros and cons. 每种方法各有利弊。

If you do wish to use this method, I would only suggest doing so if you are not collecting many customerIds and do want a lot of customerData per each customerId , or, if you are collecting many customerIds and do not want a lot of customerData per each customerId . 如果你想使用这个方法,我只会建议这样做,如果你不收集很多customerIds和确实想了很多customerData每每个customerId ,或者,如果你正在收集许多customerIds ,不想要很多的customerData每每个customerId If you store a lot of customerData for a lot of customerIds , you will consume a very large amount of memory. 如果存储了大量的customerData了很多customerIds ,你会消耗非常大量的内存。

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

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