JavaScript中数组元素删除的七大方法汇总

在JavaScript中,除了Object之外,Array类型恐怕就是最常用的类型了。与其他语言的数组有着很大的区别,JavaScript中的Array非常灵活。今天我就来总结了一下JavaScript中Array删除的方法。大致的分类可以分为如下几类:

  1. length
  2. delete
  3. 栈方法
  4. 队列方法
  5. 操作方法
  6. 迭代方法
  7. 原型方法

下面我对上面说的方法做一一的举例和解释。

一、length

JavaScript中Array的length属性非常有特点一一它不是只读的。因此,通过设置这个属性可以从数组的末尾移除项或添加新项,请看下面例子:

var colors = ["red", "blue", "grey"];   //创建一个包含3个字符串的数组
colors.length = 2;
console.log(colors[2]);  //undefined

二、delete关键字

 var arr = [1, 2, 3, 4];
 delete arr[0];
 
 console.log(arr);   //[undefined, 2, 3, 4]

可以看出来,delete删除之后数组长度不变,只是被删除元素被置为undefined了。

三、栈方法

 var colors = ["red", "blue", "grey"];
 var item = colors.pop();
 console.log(item);      //"grey"
 console.log(colors.length);    //2

可以看出,在调用Pop方法时,数组返回最后一项,即”grey”,数组的元素也仅剩两项。

四、队列方法

队列数据结构的访问规则是FIFO(先进先出),队列在列表的末端添加项,从列表的前端移除项,使用shift方法,它能够移除数组中的第一个项并返回该项,并且数组的长度减1。

 var colors = ["red", "blue", "grey"];
 var item = colors.shift();
 console.log(item);      //"red"
 console.log(colors.length);    //2

五、操作方法

splice()恐怕要算最强大的数组方法了,他的用法有很多种,在此只介绍删除数组元素的方法。在删除数组元素的时候,它可以删除任意数量的项,只需要指定2个参数:要删除的第一项的位置和要删除的项数,例如splice(0, 2)会删除数组中的前两项。

 var colors = ["red", "blue", "grey"];
 var item = colors.splice(0, 1);
 console.log(item);      //"red"
 console.log(colors);    //["blue", "grey"]

六、迭代方法

所谓的迭代方法就是用循环迭代数组元素发现符合要删除的项则删除,用的最多的地方可能是数组中的元素为对象的时候,根据对象的属性例如ID等等来删除数组元素。下面介绍两种方法:

第一种用最常见的ForEach循环来对比元素找到之后将其删除:

var colors = ["red", "blue", "grey"];

colors.forEach(function(item, index, arr) {
  if(item == "red") {
      arr.splice(index, 1);
  }
});

第二种我们用循环中的filter方法:

 var colors = ["red", "blue", "grey"];
 
 colors = colors.filter(function(item) {
     return item != "red"
 });
 
 console.log(colors);    //["blue", "grey"]

代码很简单,找出元素不是”red”的项数返回给colors(其实是得到了一个新的数组),从而达到删除的作用。

七、原型方法

通过在Array的原型上添加方法来达到删除的目的:

  Array.prototype.remove = function(dx) {
  
      if(isNaN(dx) || dx > this.length){
          return false;
      }
  
      for(var i = 0,n = 0;i < this.length; i++) {
          if(this[i] != this[dx]) {
              this[n++] = this[i];
         }
     }
     this.length -= 1;
 };
 
 var colors = ["red", "blue", "grey"];
 colors.remove(1);  console.log(colors); //["red", "grey"]

在此把删除方法添加给了Array的原型对象,则在此环境中的所有Array对象都可以使用该方法。尽管可以这么做,但是我们不推荐在产品化的程序中来修改原生对象的原型。道理很简单,如果因某个实现中缺少某个方法,就在原生对象的原型中添加这个方法,那么当在另一个支持该方法的实现中运行代码时,就可能导致命名冲突。而且这样做可能会意外的导致重写原生方法。

You may also like...

100 Responses

  1. Pejcuw说道:

    order escitalopram 10mg for sale buy prozac for sale revia online

  2. Axvdga说道:

    buy generic furosemide online furosemide for sale buy albuterol tablets

  3. Vzngnm说道:

    oral strattera zoloft medication buy generic sertraline 100mg

  4. Zvvvhu说道:

    ursodiol 150mg over the counter order bupropion 150mg for sale zyrtec 10mg cheap

  5. Kqsqgv说道:

    order azithromycin pill buy omnacortil 10mg generic buy generic gabapentin 800mg

  6. cbd vapes canada说道:

    whoah this blog is fantastic i really like studying your posts. Stay up the good paintings! You recognize, lots of people are looking around for this info, you could aid them greatly.

  7. Swheeh说道:

    deltasone 10mg over the counter prednisone 40mg without prescription order amoxil 500mg pill

  8. Cnfozx说道:

    order the contraceptive pill online morning after pill order online best pills for premature ejaculation

  9. Mzkmvz说道:

    promethazine without prescription buy erectile dysfunction pills ivermectin buy canada

  10. Fvrtpo说道:

    best medications for stomach ulcers bacterial infection of the urinary tract urinary tract infection prevention medication

  11. Jglwwx说道:

    buy cymbalta 40mg sale buy modafinil cheap provigil uk

  12. Ufllpj说道:

    over the counter antifungal creams how to not spread hsv2 high blood pressure medications generic

  13. Ktkxjc说道:

    buy generic cyproheptadine nizoral 200mg brand ketoconazole for sale

  14. Mgfida说道:

    best prescription medicine for shingles diabetes type 2 treatment nhs names of diabetic drugs

  15. I m going to bookmark your web site and maintain checking for brand spanking new information.

  16. Lhrkzt说道:

    buy cheap generic provera buy praziquantel medication hydrochlorothiazide drug

  17. Yuqmsj说道:

    stop smoking nhs near me strength supplements for women buy painkillers online usa

  18. Kqminc说道:

    letrozole online buy albenza 400 mg generic abilify 20mg tablet

  19. Dpvhvj说道:

    get insomnia medication online weight loss medication online prescription buy wegovy without a prescription

  20. Nvjodp说道:

    buy alfuzosin pills for sale brand uroxatral 10mg strongest heartburn medicine

  21. Gsqmtl说道:

    minocycline 100mg tablet buy ropinirole online cheap buy ropinirole for sale

  22. Bjtbun说道:

    adult acne causes in female where can i buy trileptal trileptal 300mg generic

  23. Kwrzny说道:

    brand catapres order antivert 25mg pill order generic spiriva

  24. Itdslq说道:

    purchase calcitriol online where can i buy calcitriol tricor 160mg sale

  25. Jajgwk说道:

    trimox 250mg generic order amoxicillin 500mg pill buy biaxin 500mg pill

  26. Zpzfhs说道:

    cheap essay help free online slot machines free online roulette

  27. Kzdooi说道:

    buy custom research paper suprax pills order cefixime 100mg online cheap

  28. Aajupz说道:

    purchase aspirin online online gambling with real payouts win real money online casino for free

  29. zoritoler imol说道:

    Somebody essentially lend a hand to make severely posts I might state. This is the first time I frequented your web page and up to now? I amazed with the analysis you made to make this actual post incredible. Excellent activity!

  30. Yakcvt说道:

    buy generic desyrel 50mg where to buy clindac a without a prescription clindamycin usa

  31. Qzpwex说道:

    cefuroxime 500mg oral axetil order online buy robaxin tablets

  32. Sqtgtu说道:

    cheap tadalafil diclofenac 50mg without prescription purchase indocin generic

  33. Uspkrs说道:

    nolvadex order order generic tamoxifen 10mg purchase symbicort generic

  34. Ceobzr说道:

    order retin gel generic order tretinoin cream without prescription cheap avana 100mg

  35. Qhkuqr说道:

    buy cleocin without prescription fildena 50mg price buy generic sildenafil

  36. Cgxmwg说道:

    buy lamictal pills for sale buy lamotrigine 200mg without prescription mebendazole 100mg ca

  37. Dnbnrg说道:

    metronidazole pill buy metronidazole 400mg generic order cephalexin 125mg online

  38. Atqota说道:

    sildenafil 50mg sale buy sildenafil without prescription estrace for sale online

  39. Prxjoz说道:

    buy diflucan generic order ampicillin 500mg pill ciprofloxacin order online

  40. Xlwubi说道:

    help writing essays website to write essays help me with my essay

  41. Hmxdri说道:

    order spironolactone 25mg without prescription buy aldactone generic buy propecia 5mg online cheap

  42. Kgyowg说道:

    buy domperidone without prescription coreg 25mg brand buy tetracycline cheap

  43. Uwqrhe说道:

    flomax 0.4mg for sale oral flomax 0.2mg generic simvastatin 20mg

  44. Sgyyuw说道:

    generic buspar 10mg purchase zetia pill amiodarone 100mg uk

  45. Gksvbi说道:

    ranitidine drug buy generic zantac celecoxib sale

  46. Teexng说道:

    order allopurinol 300mg pill order clobetasol online buy rosuvastatin 20mg pills

  47. Wlpewm说道:

    sumatriptan over the counter buy levofloxacin without a prescription avodart us

  48. Hppqzv说道:

    order nexium for sale buy remeron generic topamax where to buy

  49. Ruarwr说道:

    buy astelin online zovirax 800mg price irbesartan 300mg cost

  50. Abkuhc说道:

    order pepcid pills where to buy cozaar without a prescription order tacrolimus online

  51. Olhggr说道:

    orlistat 120mg over the counter where to buy mesalamine without a prescription diltiazem 180mg usa

  52. Smbciu说道:

    buy medex generic paroxetine 10mg uk buy generic metoclopramide over the counter

  53. Imbmeg说道:

    purchase glimepiride pills buy amaryl paypal buy arcoxia 120mg online

  54. Jlaojp说道:

    buy pamelor 25mg pill generic paracetamol order generic anacin

  55. Yjgcnv说道:

    buy inderal 10mg without prescription oral inderal plavix 150mg usa

  56. Pxmbyf说道:

    buy alendronate online order colcrys 0.5mg sale buy nitrofurantoin 100mg online cheap

  57. Захотелось новых ощущений и я решил попробовать поиграть в онлайн казино. Сайт caso-slots.com стал моим проводником в этот мир. Теперь у меня есть список популярных казино и тех, где можно получить бонус на первый депозит.

  58. Rpwbkz说道:

    buy baclofen 10mg pill purchase endep for sale buy generic toradol

  59. Ctsqdn说道:

    order loratadine 10mg generic buy loratadine tablets order dapoxetine 90mg online

  60. Uvjooy说道:

    buy lioresal without a prescription buy toradol 10mg without prescription toradol 10mg drug

  61. Zayngk说道:

    order dilantin 100 mg pill flexeril where to buy oxybutynin 2.5mg pills

  62. Idzuzj说道:

    order generic aceon 4mg buy generic clarinex fexofenadine 120mg usa

  63. Txgkkt说道:

    levitra 10mg drug lanoxin 250 mg cheap tizanidine 2mg pills

  64. Мечтаете об идеальном отпуске на Черноморском побережье? Туапсе – великолепный выбор, а мы знаем, как сделать ваш отдых неповторимым! Благодаря богатому опыту и профессионализму, мы подберем отель, который превзойдет все ваши ожидания.

    Позвольте себе роскошь наслаждаться каждым моментом отдыха, погружаясь в атмосферу комфорта и уюта. Ваши пожелания – наш приоритет. Хотите просыпаться под шум моря или предпочитаете тишину горных склонов? Мы найдем идеальный вариант для вас.

    Каждый отель в Туапсе, предложенный нами, гарантирует высокий стандарт обслуживания, чистоту, удобство и комфорт. Мы верим, что отдых должен быть настоящим наслаждением, и готовы предложить вам лучшее!

  65. Wdttgu说道:

    purchase clomid online cheap azathioprine ca buy generic azathioprine 50mg

  66. Однажды поздно ночью я осознал, что срочно нуждаюсь в финансах. Портал wikzaim стал моим спасением. Благодаря быстрому и удобному сервису, я получил займ сразу от двух микрофинансовых компаний, что помогло мне в решении непредвиденных финансовых вопросов.

  67. Nnovjq说道:

    casino online buy augmentin 375mg for sale levothroid tablet

  68. Eetfnc说道:

    amantadine 100 mg generic buy atenolol generic aczone 100mg pill

  69. Недавно мне понадобилось 12 000 рублей на ремонт холодильника. На форуме мне посоветовали посетить yelbox.ru. Там я нашел подробную информацию о том, как взять онлайн займ на карту и список проверенных МФО. И узнал, что есть займы без процентов!

  70. Rdvffq说道:

    play slots for real money united states play blackjack online for real money buy ivermectin 3mg for humans

  71. Zdkulz说道:

    legitimate online slots for money blackjack for money ventolin inhalator without prescription

  72. Rytzbn说道:

    cost protonix brand lisinopril pyridium 200 mg drug

  73. Ipzodg说道:

    online roulette free best online casino for real money furosemide pills

  74. Rvxvju说道:

    buy atorvastatin 10mg generic buy lipitor 80mg online oral amlodipine

  75. Cfgfsc说道:

    azipro online buy buy cheap generic neurontin purchase gabapentin online cheap

  76. Hazhvy说道:

    isotretinoin 10mg brand buy generic absorica zithromax drug

  77. Cxhdna说道:

    buy cefdinir pills purchase cefdinir online buy lansoprazole 30mg online

  78. Dokxjf说道:

    order generic modafinil 100mg promethazine 25mg pill brand deltasone 10mg

  79. Xkcbhv说道:

    cenforce online buy buy chloroquine for sale order aralen 250mg online cheap

  80. Dsbukt说道:

    buy tadalafil 5mg sale order tadalafil generic purchase sildenafil online cheap

  81. Pcsydq说道:

    micardis online oral plaquenil 400mg molnupiravir 200mg cost

  82. Oktbwy说道:

    buy prilosec 10mg online cheap buy metoprolol 100mg generic buy metoprolol generic

  83. Zfvqnh说道:

    premarin 0.625mg without prescription oral premarin 0.625mg viagra fast shipping

  84. Vzsgsr说道:

    xalatan brand purchase rivastigmine online oral rivastigmine

  85. Iyccdz说道:

    vasotec us buy cheap generic enalapril purchase duphalac bottless

  86. Rbtsve说道:

    order mestinon 60 mg for sale buy maxalt medication order rizatriptan 10mg online

  87. Yurhjw说道:

    generic ferrous sulfate 100mg buy actonel 35mg online cheap how to get betapace without a prescription

  88. Gbklnt说道:

    order prasugrel 10mg online tolterodine 1mg pills detrol over the counter

  89. Zbvybx说道:

    buy generic monograph order etodolac buy cilostazol online

  90. Gjsyxb说道:

    buy florinef 100mcg generic buy fludrocortisone cheap imodium order

  91. Xmcdqn说道:

    buy dydrogesterone 10 mg order forxiga 10 mg sale buy empagliflozin 25mg pills

  92. Pqsvrx说道:

    purchase meloset generic buy danocrine 100 mg pills order danocrine generic

  93. Lcijqb说道:

    buy dipyridamole medication brand felodipine pravachol 10mg pill

  94. Lpcbez说道:

    aspirin 75mg brand levofloxacin 500mg oral buy imiquimod medication

  95. Aeojdx说道:

    generic precose 50mg glyburide cheap griseofulvin drug

  96. Cokaey说道:

    buy generic minoxytop buy ed pills for sale medication for ed

  97. Expads说道:

    where to buy zaditor without a prescription pill ketotifen 1mg order tofranil online cheap

  98. Olxigs说道:

    order cialis 5mg without prescription buy sildenafil pill sildenafil professional

  99. Wtfeit说道:

    buy fenofibrate cheap tricor 200mg drug tricor 200mg canada

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注

CAPTCHAis initialing...