zoukankan      html  css  js  c++  java
  • JavaScript数组方法

    JavaScript数组方法总结(上)

    2017-03-05 13:26:35503浏览0评论

    JavaScript中提供了多种数组方法,如下:

    1. 转换方法—toLocaleString()方法、toString()方法、valueOf()方法
    2. 栈方法——push()方法、pop()方法
    3. 队列方法——shift()方法、unshift()方法
    4. 重排序方法——reverse()方法、sort()方法
    5. 操作方法——concat()方法、slice()方法、splice()方法
    6. 位置方法——indexOf()方法、lastIndexOf()方法
    7. 迭代方法——every()方法、filter()方法、forEach()方法、map()方法、some()方法
    8. 归并方法——reduce()方法、reduceRight()方法

    转换方法:

    ①:toString()方法返回由数组中每个值的字符串形式拼接并且以逗号相隔的字符串
    ②:valueOf()方法返回的还是数组
    ③:toLocaleString()方法也会返回一个数组值以逗号相隔的字符串,但与toString()方法不同的是在返回日期对象时格式不同。

    具体看一下例子:

    var colors=["red","blue","green"];
    console.log(colors.toString());    //"red,blue,green"
    console.log(colors.valueOf());    //red,blue,green
    console.log(colors.toLocaleString());    //"red,blue,green"
    
    //toLocaleString()方法与toString()方法在返回日期对象时格式不同
    var today=new Date();
    console.log(today.toString());    //    Sun Mar 05 2017 12:57:11 GMT+0800 (中国标准时间)
    console.log(today.toLocaleString());    //    2017/3/5 下午12:57:11

    栈方法:

    ①:push()方法可以接受任意数量的参数,逐个添加到数组末尾,返回修改后数组的长度
    ②:pop()方法从数组末尾移除最后一项,返回被移除的项
    具体看下面例子:

    var arr=new Array();    //使用构造函数创建数组
    var count=arr.push("red","blue");    //push()返回数组长度
    
    console.log("count="+count);    //count=2
    console.log(arr);    //red,blue
    
    count=arr.push("black");    //count=3
    
    var item=arr.pop();
    console.log("item="+item);//pop返回被移除的项--item=black

    队列方法:

    ①:shift()方法移除数组的第一次项并返回该项
    ②:unshift()方法在数组前端添加任意项,并返回新数组的长度

    具体看一下例子:

    var colors=new Array();    //创建数组
    var count=colors.unshift("red","green");    //在数组前端添加两项
    console.log(count);    //2
    
    count=colors.unshift("black");     //此时数组各项顺序为"black","red","green"
    console.log(count)    //3
    
    item=colors.shift();
    console.log(item);    //black

    由栈方法跟队列方法可知,在这两种方法中添加数组项的方法返回新数组的长度,移除数组项的方法返回被移除项

  • 相关阅读:
    multipath路径残留导致虚拟机无法重启
    multipath配置错误导致的云平台虚拟机挂载云硬盘失败
    kubernetes v1.8.3安装coredns
    helm安装chart----percona-xtradb-cluster实践记录
    elasticsearch性能调优相关
    nova hypervisor-list无法执行,其他api均正常
    珍爱面经
    猫眼面经
    头条面经
    阿里秋招面经
  • 原文地址:https://www.cnblogs.com/lxg0/p/6736869.html
Copyright © 2011-2022 走看看