雖然只有一個字母之差,但用法卻差很多,我今天就被坑了。
var g=["a","b","c","d","e","f","y"];
console.log(g.slice(2,5)); // 打印出來的是 c d e
console.log(g.splice(2,5)); //打印出來的是 c d e f y
*slice(2,5):2是起始位置的下標,5是終止位置的下標,所以第二個數總是大于第一個數的
當只有參數的時候(slice(3)),就是從下標3開始,到末尾。
*splice(2,5):2還是起始位置的下標,但5是選擇5個數,第二個數可大于可小于,不受第一個數的影響,也可以說是刪除5個數
總結: slice:是截取用的 splice:是做刪除 插入 替換用的
上邊已經說了splice的刪除,下邊介紹下插入和替換:
插入:.splice(1,0,"u"),1是起始位置下標,0是默認參數,但必須填,u是加入的項,如:
var g=["a","b","c","d","e","f","y","t","p"];
g.splice(1,0,"u");
console.log(g); // 打印出來的是 "a", "u", "b", "c", "d", "e", "f", "y", "t", "p"
替換:.splice(1,2,"k"); 1是起始位置的下標,2是刪除2項,在刪除的那個位置加入的k。
var g=["a","b","c","d","e","f","y","t","p"];
g.splice(1,2,"k");
console.log(g); // 打印出來的是 "a", "k", "d", "e", "f", "y", "t", "p";