zoukankan      html  css  js  c++  java
  • Javascript中对数组处理的函数汇总

       数组类型是JS中非常常见的类型,而且JS里的数组与其他多数语言中的数组有所不同,它的数组里每一项可以存放任何一种类型的数据,也就是说数组的第一项放的是字符串,第二项可以放数字或对象都没问题。而且JS中的数组长度是任意收缩的,可以人为的规定数组长度,不过不规定也没问题,它会随着数组里项的数量自动改变长度。

        在介绍数组的函数之前,先介绍两种判断对象是否是数组的方法:

    1. 运用instanceof操作符

    实例:

    var arr = [1, 2, 3];
    alert(arr instanceof Array);    //true
    var obj = new Object();
    alert(obj instanceof Array);    //false

    2.运用Array中的isArray方法

    实例:

    Array.isArray([1, 2, 3]);    //true
    Array.isArray(new Array());  //true
    Array.isArray([]);          //true
    Array.isArray({});          //false
    Array.isArray('string');    //false
     
    数组的使用范围很广,功能也很强大,下面就总结下JS中对数组进行处理的函数吧

    1. 数组转换为字符串

    方法1: toString()

    var color = ["red", "blue", "green"];
    alert(color.toString());             //red,blue,green
    alert(typeof(color.toString()));     // string

    方法2: join() 此方法接受一个参数作为分隔符分隔字符串,然后返回包含所有数组项的字符串

    var color = ["red", "blue", "green"];
    alert(color.join(" "));             // red blue green
    alert(color.join("$"));             // red$blue$green

    2.删除数组最后一项

    方法: pop()

    var color = ["red", "blue", "green"];
    var last = color.pop();             // green
    alert(color);                      // red,blue

    3.在数组最后插入若干项

    方法:push()

    var color = ["red", "blue", "green"];
    var count = color.push("black", "yellow");
    alert(count);                    // 5

    4.在数组前端插入若干项

    方法:unshift()

    var color = ["red", "blue", "green"];
    var count = color.unshift("black", "yellow");
    alert(count);                 //5
    alert(color);                 //black,yellow,red,blue,green

    5.删除数组前端第一项

    方法:shift()

    var color = ["red", "blue", "green"];
    var first = color.shift();
    alert(first);             //red
    alert(color);             //blue,green
    6.为数组排序
    方法:sort([compareFunction])
    方括号中的compareFunction是可选参数,它代表为数组排序需要遵循的规则,如果没有此参数则默认降数组中的元素都转换成ASICII码进行排序。
    var arr1 = [9, 30, 5, 17];
    arr1.sort();     //[17, 30,  5, 9]
    var arr2 = [China, america, Japan];
    arr2.sort();     //[China, Japan, america]
    若定义了比较函数,并将它以参数形式传给sort函数,则排序按照相关规则进行,例如对只有数字的数组进行从小到大的排序:
    function compare(a, b) {
        return a - b;
    }
    var arr3 = [39, 10, 9, 3];
    arr3.sort(compare);     //[3, 9, 10, 39]
  • 相关阅读:
    【转】解决warning C4003: “min”宏的实参不足
    【转】C++文件读写详解(ofstream,ifstream,fstream)
    【转】OBJ 文件格式
    Leap::HandList Class Reference 手列表类参考
    Leap::Frame Class Reference 帧类参考
    Leap::DeviceList Class Reference 设备列表类参考
    webpack CommonsChunkPlugin
    使用sass random 函数随机分配cdn hostname
    114. Flatten Binary Tree to Linked List (leetcode)
    windows 安装 ruby 和 sass
  • 原文地址:https://www.cnblogs.com/kongxy/p/4367107.html
Copyright © 2011-2022 走看看