虽然只有一个字母之差,但用法却差很多,我今天就被坑了。
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";