前端基础学习

数组之splice()和slice()

2020-03-16  本文已影响0人  小雪洁
<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>splice与slice数组中间元素管理</title>
    </head>
    <body>
        <script>
            //数组截取 arr.slice(index1,index2), 截取范围是[index1,index2)
            let a=[1,2,3,4,5];
            console.log(a.slice(1));//返回截取的元素 
            console.log(a);//原数组没有变化
            console.log(a.slice(1,4));//[2, 3, 4]
            console.log(a.slice());//[1,2,3,4,5]
            //arr.splice(index,n,item) 从第index索引开始,截取n个元素,将其替换为item
            console.log(a.splice(0,2));//[1,2]splice方法会改变原数组
            console.log(a);//[3, 4, 5]
            //替换数组中某个元素
            let b=[1,2,3,4,5];
            let c =b.splice(0,3,"hxj","ydc"); //返回的是[1,2,3]赋给c,而b中被截掉的元素由"hxj","ydc"代替
            console.log(b);//["hxj", "ydc", 4, 5]
            console.log(c);//[1, 2, 3]
            let d=[1,2,3,4,5];
            d.splice(2,1,"hxj");//将索引2的元素替换为"hxj"
            console.log(d);//[1, 2, "hxj", 4, 5]
            //往数组中任何一个位置增加元素
            let e=[1,2,3,4,5];
            e.splice(1,0,"hxj","ydc");
            console.log(e);//[1, "hxj", "ydc", 2, 3, 4, 5]
            let f=[1,2,3,4,5];
            //f.splice(f.length,0,"hxj");
            f.splice(0,0,"hxj");//["hxj", 1, 2, 3, 4, 5]
            console.log(f);
        </script>
    </body>
</html>

上一篇下一篇

猜你喜欢

热点阅读