解释

splice(index,len,[item])它也可以用来替换/删除/添加数组内某一个或者几个值(该方法会改变原始数组)

index:数组开始下标
len: 替换/删除的长度
item:替换的值,删除操作的话 item为空

删除

//删除起始下标为1,长度为1的一个值(len设置1,如果为0,则数组不变)


var arr = ['a','b','c','d'];
arr.splice(1,1);
console.log(arr);  
//['a','c','d']; 


var arr2 = ['a','b','c','d']
arr2.splice(1,2);
console.log(arr2); 
//['a','d']

替换

//替换起始下标为1,长度为1的一个值为‘ttt’,len设置的1

var arr = ['a','b','c','d'];
arr.splice(1,1,'ttt');
console.log(arr);        
//['a','ttt','c','d'] 


var arr2 = ['a','b','c','d'];
arr2.splice(1,2,'ttt');
console.log(arr2);       
//['a','ttt','d'] 

添加

//在下标为1处添加一项'ttt'

var arr = ['a','b','c','d'];
arr.splice(1,0,'ttt');
console.log(arr);        
//['a','ttt','b','c','d'] 

 

Logo

前往低代码交流专区

更多推荐