首頁  >  文章  >  web前端  >  js學習中常遇到的陣列方法,總結很到位

js學習中常遇到的陣列方法,總結很到位

php是最好的语言
php是最好的语言原創
2018-07-27 14:13:461313瀏覽

js數組方法的總結:1、隊尾插入push,2、隊尾刪除並返回刪除的最後一項pop,3、隊首插入unshift(),4、隊首刪除shift(),5、陣列一加入陣列二concat()

1、隊尾插入push

   var colors = ["red","green"];
   colors.push("black"):
   console.log(colors); //["red","green","black"]

2、隊尾刪除並回傳刪除的最後一項pop

   var colors = ["red","green","black"];
   var item = colors.pop();
   console.log(item); //"black"

3、隊首插入unshift()

   var colors = ["red","green"];
   colors.unshift("black");
   var item = colors.pop();
   console.log(item); //"black"

4、隊首刪除shift()

   var colors = ["red","green","black"];
   colors.shift();
   console.log(colors); //["green","black"]

5、陣列一新增陣列二concat()

   var colors = ["red","green","black"];
   var colors2 = colors.concat("yellow",["blue","brown"]);
   console.log(colors); //["red","green","black"]
   console.log(colors2); //["red","green","black","yellow","blue","brown"]

6、陣列的截取slice ()
  只傳一個參數:從陣列這個參數的下標開始截取一直到陣列結束。

   var colors = ["red","green","black"];
   colors.slice(1); //["green","black"]
   console.log(colors); //["red","green","black"]

傳送兩個參數:第一個是截取開始的位置,第二個是截取結束的位置

   var colors = ["red","green","black","yellow","blue","brown"];
   colors.slice(1,3)//从位置1开始,到位置2结束["green","black"];

7、陣列的splice()方法

   有三种用法:
  • 刪除:可以刪除任意數量的項,只需指定兩個參數:第一個參數為刪除開始的位置,第二個參數為刪除項數。

  • 插入:可以向指定位置插入任意數量的項,只需提供3個參數:起始位置、0(要刪除的項數)和要插入的項。例如:splice(2,0,"red","green"),會從目前陣列的位置2開始插入字串"red"和"green"。

  • 替換: 可以向指定位置插入任意數量的項,且同事刪除任意數量的項,只需提供3個參數:起始位置、要刪除的項數和要插入的任意數量的項。插入的項數不必與刪除項數相等。例如:splice (2,1,"red","green") 會刪除目前陣列位置2的項,然後再從位置2開始插入字串。

   var colors = ["red","green","black"];
   var removed = colors.splice(0,1);
   console.log(colors); //["green","black"]
   console.log(removed); //["red"]
    
   removed = colors.splice(1,0,"yellow","orange");
   console.log(colors); //["green","yellow","orange","black"]
   console.log(removed); //[]

   removed = colors.splice(1,1,"red","purple");
   console.log(colors); //["green","red","purple","orange","black"]
   console.log(removed); //["yellow"]

8、位置方法indexOf()和lastIndexOf()

相關文章:

js陣列操作方法總結(必看篇)

JS陣列去重方法總結

#相關影片:

js陣列與物件-千鋒教育JS實戰影片教學

以上是js學習中常遇到的陣列方法,總結很到位的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn