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學習中常遇到的陣列方法,總結很到位的詳細內容。更多資訊請關注PHP中文網其他相關文章!