多功能splice()插入、删除、替换
<script type="text/javascript"> var arr=['A','B','C','D','E','F','G']; arr.splice(3,2,'苹果','葡萄'); //替换一些项 console.log(arr); </script>
<script type="text/javascript"> // 更改一些项 var arr=['A','B','c','d','e','f','g'] arr.splice(3,2,'x','y','x','斯密码'); //更改一些项 console.log(arr); </script>
<script type="text/javascript"> var arr=['a','b','c','d','e','f','g'] arr.splice(2,1,'哈哈');//更改一个项 console.log(arr); </script>
<script type="text/javascript"> var arr=['a','b','c','d','e','f','g']; arr.splice(2,4) //没有东西可以替换,就直接删除 console.log(arr); </script>
<script type="text/javascript"> var arr=['a','b','c','d','e','f','g']; arr.splice(2); console.log(arr); </script>
<script type="text/javascript"> var arr=['a','b','c','d','e','f','g']; arr.splice(2,0,'嘻嘻','哈哈'); //插入一些项 console.log(arr); </script>
二、案例 :删除数组最后五项
<script type="text/javascript"> //删除数组最后五项 var arr['a','b','c','d','e','f','g']; arr.pop(); arr.pop(); arr.pop(); arr.pop(); arr.pop(); //简化为 for(var i=0; i<arr.length; i++;){ arr[i].pop(); } //也可以 arr.splice(-5); console.log(arr); </script>