The difference between slice() and splice()

来源:互联网 发布:centos 7 dhcp ip配置 编辑:程序博客网 时间:2024/06/01 09:14

1、slice(start,stop):get specific elements from an array and has no impact on the array. stop is not necessary.

If exists,the function will extract string from start to stop(not included).
If not,from start to end.

<script>    var arr=[1,2,3,4,5];    console.log(arr.slice(1));    //2,3,4,5    console.log(arr.slice(1,3));    //2,3    console.log(arr);    //1,2,3,4,5</script>

2、splice(index,howmany,item1,…..,itemX):return elements that are deleted.
index is where to add or delete elements.
howmany is howmany elements will be deleted.
item 1…intemX (not necessary)are elements that will be added to the array.It will change the original array.

<script>    var arr=[1,2,3,4,5];    console.log(arr.splice(1,2));    //2,3 (arr:[1,4,5])    console.log(arr.splice(1,1,6));    //4 (arr:[1,6,5])    console.log(arr);    //1,6,5</script>

▲:think about :substr() and substring()

0 0
原创粉丝点击