zoukankan      html  css  js  c++  java
  • 数组方法slice和splice

    slice(start , end)截取数组

    1.方法介绍:不改变原数组,返回截取出来的数组
    2.参数两个从哪里开始到哪里结束,第一个参数(必选),可以是负数,代表从右边开始截取,第二个参数,代表到哪里结束,可以是负数,代表从右边查的索引位置。

     // 字面量声明的方式,返回的是字符串 
    var names=["George","John","Thomas"];
    console.log(names.slice(1,3)); // eo
    console.log(names); // George,John,Thomas
    
    // new方式声明的数组,返回的是数组
    var arr = new Array(3);
    arr[0] = "George";
    arr[1] = "John";
    arr[2] = "Thomas";
    console.log(arr.slice(1,3)); // 输出为["John", "Thomas"]
    console.log(arr);  // ["George", "John", "Thomas"]
    

    splice 方法向/从数组中添加/删除项目

    1.方法介绍:会改变原数组,返回操作后的数组
    2.参数arrayObject.splice(index,howmany,item1,.....,itemX)

    index:从什么位置开始,正负整数都可以(必须)
    howmany:删除的个数,0代表不删除(W3C必须,测试不传参数代表到最后一位)
    item:代表向数组中添加的元素
    
    // 删除元素
    var arr = new Array(3)
    arr[0] = "George"
    arr[1] = "John"
    arr[2] = "Thomas"
    console.log(arr.splice(1)); // 输出为["John", "Thomas"]
    console.log(arr); // 输出为["George"]
    
    // 添加元素
    var arr = new Array(3)
    arr[0] = "George"
    arr[1] = "John"
    arr[2] = "Thomas"
    console.log(arr.splice(1,0,"bonly")); // 输出为空数组[]
    console.log(arr); // 输出为["George", "bonly", "John", "Thomas"]
    
  • 相关阅读:
    .NET Core使用RabbitMQ
    微信openid和unionid区别
    .Net Core 中GC的工作原理
    .Net Core服务监控报警指标上报Prometheus+Grafana
    .Net Core基础的健康检查
    了解数据库的四种隔离级别
    IdentityServer使用ssl证书生成token
    IdentityServer客户端授权模式
    IdentityServer用户名密码模式
    IdentityServer4学习笔记汇总(实现传送门在底部)
  • 原文地址:https://www.cnblogs.com/bonly-ge/p/9435656.html
Copyright © 2011-2022 走看看